Tricks you should know when working JS

Tram Ho

When I started learning Javascript , I found some tricks and today I will share with you some nice things, I think it will help you a lot in the process of coding.

1. Filter Unique Values

Set is included in es6, along with … spread operator , we can use it to create a new array with unique values.

This trick works for array with primitive type : undefined , null , boolean , string and number (If you have an array containing object , function , and array , it doesn’t apply Set) !!!

2. Every and Some

The function every and some not two commonly used functions. But it is very useful in certain cases.

every : run through each element and test a certain condition. If pass through all elements in the array will return true . If an element fails the condition returns false

some : run through each element and test a certain condition. If an element is found to be eligible, return true . If all elements in the array are run without finding an appropriate condition, false

3. Convert to Boolean

In addition to the true boolean values true and false , all values ​​in Javascript are truthy except 0 , '' , null , undefined , NaN is falsy

We can switch between true and false using ! ( negative operator ), operator ! can convert a type into a boolean

This type of conversion is very convenient in conditional statements.

4. Convert to String

Quickly convert a number into a string , we can use the + '' operator + ''

5. Get the Last Item (s) in an Array

The slice () method in an array can take a negative vowel, and if you include a negative integer, it will get from the end of an array instead of the starting point.

Reference source:

Share the news now

Source : Viblo