11 Useful JavaScript Tips

Tram Ho

In daily programming work we often encounter problems such as: checking key to see if they exist, conditional manipulation of data, filtering value ​​in array , etc.

Here I list some common cases that I personally love and are very helpful to make the code shorter and clearer. Some of you will wonder why not use the library, the library already has it all.

  1. Sometimes killing chickens doesn’t need a buffalo knife
  2. I always make good use of the built-in functions of js first

1. Conditions when adding Properties to the object

2. Check if a Property exists in an object

We can use keyword in to check if the property exists in Object

3. Destructuring object with Dynamic key

We can also set an alias name for a variable that has been Destructuring

4. Loop an object to access key and value simultaneously

The key and the value can be accessed at the same time using the entries . function

5. Prevent error when accessing any key that does not exist in the object by using optional string ( ?. )

Warning: optional string is used when you are not sure whether its Property exists or not in the data. If you are sure that the keys must be in the data and if they are not, then you should throw error to raise an lỗi instead of preventing them.

6. Check for falsy value values ​​in an array

7. Remove duplicate values ​​in array.

I use this function very often (quickly)

Note: this is a feature of ES6.

8. Check if a variable is of type array or not

Since array is essentially an array {0:{}, 1:{}, 2:{}....} so typeof it will return the value as object

9. Convert String to Number and Number to String using ‘ + ‘ . operator

The + operator is a special operator, so its position also determines its meaning in each specific case.

10. Conditionally assign other values ​​when the value is null and undefined using the nullish coalescing operator ( ?? )

Many of you also confuse between ?? with the OR operator ( || )

The OR operator is used when you want to assign a different value according to the condition if the value is not true . Meaning if it is one of the following values ​​( 0 , ' ' , null , undefined , false , NaN )

11. Boolean conversion using the !!

It’s all the same, many of you still have questions !! what is different from !

Oh so if it was….

Actually it only has ! and !! only from the 3rd up oil on it is simply the negation of !! never mind.

Roundup

As always, I hope you enjoyed this article and learned something new.

Thank you and see you in the next posts!

If you find this blog interesting, please give me a like and subscribe to support me. Thank you.

Ref

Share the news now

Source : Viblo