DEV Community

Cover image for 5 useful javascript tricks for begginers.
Ratul
Ratul

Posted on • Updated on

5 useful javascript tricks for begginers.

In this post, I will show you 5 awesome javascript tricks which will make your life more easier. And will help you to become a better developer. So if you are interested, continue reading.

Trick-1: Remove duplicates from an Array!

This trick is pretty simple. Suppose I have an array which is containing number, strings and booleans. And in this array I want to make sure, that there's no duplicate item. So how do you do do that?

const array = [1, 2, 3, 2, 1, true, true, false, 'Ratul', 1, 5];
const filtered__array = [...new Set(array)];
console.log(filtered__array) // [ 1, 2, 3, true, false, 'Ratul', 5 ]
Enter fullscreen mode Exit fullscreen mode

Simple!

Trick-2: Turn a Decimal Number to a integer.

This one is a pretty straight forward trick. Let me show you.

const number = 23.6565
console.log(number | 0);
Enter fullscreen mode Exit fullscreen mode

Isn't it so simple!

Trick-3: Getting the Last Value of an Array!

Suppose you have an array of something. Now if you want to have the last item of the array, how will you do that?

const array = [1, 2, 3, 4, 5]
const last_Item = array.slice(-1)
console.log(last_Item)

Enter fullscreen mode Exit fullscreen mode

Here we go! Now if you put -2 instead of -1, you will get the last two values of the array and then if you give -3 instead of -2, you will get the value of last three index's and so on.

Trick-4: Get a random index value from an array.

Suppose we are doing a lottery programme. We have an array which is containing the names of the prticipants. Now we want only one user randomly from the array to decide a winner.

const participants = ['Ratul', 'George', 'july', 'Padrik', 'G']
const winner = participants[Math.floor(Math.random() * participants.length)]
console.log(winner) // july was the winner 😊
Enter fullscreen mode Exit fullscreen mode

Trick-5: Detect the most lengthy word in an array

Create an array and add some different strings. Now print the most lengthy string of this array.

const array = ['Apple', 'Pine-apple', 'Banana', 'Jack-fruit']

let most_lengthy_string = ''
array.forEach((item) => {
  if (item.length > most_lengthy_string.length) {
    most_lengthy_string = item
  }
})
console.log(most_lengthy_string)
Enter fullscreen mode Exit fullscreen mode

Simple! So let me explain you what's going on here. Firstly we have array which is containing some strings. And After that, I have created a variable which is containing an empty string. And now, to detect the most lengthy string in this array, I need to take a look at all of the array items So I have looped through the array. And if the array's item length is greater that the length of our "most_lengthy_string" The we are reassigning the value of the variable and after all I am just printing out the variable. That's all!

Conclusion

Thanks for reading this article. Hope you enjoyed that. If you have any doubt regarding that post, please let me know. And make sure you follow me to recieve all the informational posts just like that.

:)

Discussion (30)

Collapse
danim47c profile image
Daniel Mateos

I think the best way you can obtain the most lengthy string in an array is this:

const mostLengthy = someArray
    .reduce((acc, i) =>
        i.length > acc.length
             ? i
             : acc
)
Enter fullscreen mode Exit fullscreen mode
Collapse
coderslang profile image
Coderslang: Become a Software Engineer

That's a good one, although it might be useful to first filter out nulls and undefineds from the array:

const mostLengthy = someArray
    .filter(item => item)
    .reduce((acc, i) => i.length > acc.length ? i : acc);
Enter fullscreen mode Exit fullscreen mode
Collapse
mdegoys profile image
Matthieu • Edited on

You can also do this way I believe (sort by the length of the words in descending order, then pick the first one).

const mostLengthy = someArray.sort((x, y) => y.length - x.length)[0] 
Enter fullscreen mode Exit fullscreen mode

Maybe it's more understandable ? But I agree reduce is great :).

Collapse
ratuloss profile image
Info Comment hidden by post author - thread only accessible via permalink
Ratul Author

useful :)

Collapse
nibelune profile image
Benoît Schiex • Edited on

last_Item = arr.slice(-1) would not return the last item but a new array containing the last item.

you can do :

const lastItem = arr[arr.length-1]
const lastItem = arr.slice(-1)[0]
const lastItem = arr.slice(-1).pop()
const [lastItem] = arr.slice(-1)
Enter fullscreen mode Exit fullscreen mode
Collapse
ratuloss profile image
Info Comment hidden by post author - thread only accessible via permalink
Ratul Author

wow nice. !

Collapse
jonrandy profile image
Jon Randy
const last_item = array.reverse()[0]
Enter fullscreen mode Exit fullscreen mode
Collapse
cursorsdottsx profile image
[Cursors]

that one mutates the array, though

Collapse
jonrandy profile image
Jon Randy

Yeah. I always wondered why they decided to make it like that

Collapse
lucasgiraldelli profile image
Info Comment hidden by post author - thread only accessible via permalink
Lucas Giraldelli

Any documentation about that pipeline that converts into 'normal' number?

Collapse
nibelune profile image
Benoît Schiex

This is a bitwise or.
Since bitwise operations only make sense on integers, the decimal part is truncated.

Collapse
lucasgiraldelli profile image
Lucas Giraldelli

thank you!

Collapse
vbubblery profile image
Juncheng • Edited on

Try with this:

const number = 23.6565
console.log(~~number);
const string = "24"
console.log(+24)
Enter fullscreen mode Exit fullscreen mode
Collapse
captainofphb profile image
Info Comment hidden by post author - thread only accessible via permalink
CaptainOfPhB

I think those are basic skills of javascript developer(maybe you are a new bee), and the second trick is not recommended, Math.round/Math.floor/Math.ceil are better choice, which will make your code more readable.

Collapse
coderdeepansh profile image
Deepansh Dash

Thanks it is useful.

Collapse
aspiiire profile image
Aspiiire

That is really useful, thank you 😁

Collapse
baikai223 profile image
baikai223

获取数组的最后一项数据使用数组的api方法不是更好吗?arr.pop()

Collapse
ratuloss profile image
Ratul Author

I don't understand what you have said :|

Collapse
baikai223 profile image
baikai223

Wouldn't it be better to use pop() instead of slice()?

Thread Thread
ratuloss profile image
Ratul Author

you can use what ever you want. ......I know how to do that with slice so I have shown with slice. If you know how to do that with pop() you can use pop. :)

Collapse
ianwijma profile image
Info Comment hidden by post author - thread only accessible via permalink
Ian Wijma

Not 100% sure you should the weird int casting. Not everyone knows about it. And could cause confusion when reading it. Maybe just use parseInt. 😁 Really Cool post though!!

Collapse
fabioluciano profile image
Info Comment hidden by post author - thread only accessible via permalink
Fábio Luciano

By normal number, did you mean integers?

Collapse
ratuloss profile image
Ratul Author

Small mistake. It will be interger. 😅😥

Collapse
devendra0110 profile image
Devendra Gaud

I'm still wondering how the logic works in Trick-2.

Collapse
ratuloss profile image
Ratul Author

Small trick ;)

Collapse
devendra0110 profile image
Devendra Gaud

Ok, I just discovered two other ways similar to that trick.

console.log(~~5.95) 
console.log(5.95 >> 0)
Enter fullscreen mode Exit fullscreen mode

And I'm more confused now.

Thread Thread
ratuloss profile image
Ratul Author

you can use what ever you want. Both of the tricks does the same thing. Or you can also use Math.floor() or Math.round()

Collapse
kamalhossain profile image
Kamal Hossain

thanks for sharing.

Collapse
rocksuvel profile image
suvel rathneswar⚛️

Helpful ☺️

Some comments have been hidden by the post's author - find out more