8 ways to write JavaScript like a pro!

Tram Ho

1. Arrow functions

JS ES6 release Arrow functions that let you write functions more clearly and quickly! Instead of having to declare the function like this:

Then you can declare the same with less code:

It can be even simplified if your function only has one expression:

2. Spread Operator

Spread syntax allows iterable objects such as Array or String to be declared extensively in function cll or in elements of array literals or Object . (If the reader does not understand, the example will understand immediately)

2.1. Creates a new array that has an element of an array

2.2. A better way to join arrays

2.3. Use as parameter passed to the function

3. Rest Operator

Rest syntax looks exactly like the spread syntax , except that rest syntax is used to combine arrays and objects. In other words, rest syntax is the opposite syntax of spread syntax . Spread syntax allows to expand an array into its own element, while rest syntax aggregates everything into a single element.

P / s: If you still do not understand, you can understand in the way of the translator as follows:

  • Spread syntax is for passing into a function=> Use by function call, declare object, declare array, …
  • Rest syntax is for fetching all elements passed in with a single variable=> Use inside the function

The last parameter of the above function is prefixed ... causing all remaining parameters to be placed in the same array.

4. Fill arrays

Create a simple array with one line of code.

4.1. Array with 5 elements is empty string

4.2. Array with numbers from 0 to 4

5. Computed property names

ES6 supports a new syntax called computed property names that allows you to enclose the expression in square brackets [] , the expression in it will be used as a key in that object .

6. Good ways to console.log()

6.1. Use console.table() when you have an array of objects .

=> Result:

6.2. Make print results stand out more with CSS and the % sign

=> Result:

6.3. Log multiple objects at once to save space and also make it easier to read.

=> Result:

7. Object destructuring

Get rid of the duplicate code by destructuring the properties of the object you need.

Destructure inside the function syntax by wrapping the property name in curly braces {}

Or pass an object and declare the variable name matching the property name of that object . This way will be better if there are many destructure objects in the function.

8. Use reduce() , map() and filter() instead of regular loops.

8.1. Use reduce() to calculate the value of the array.

8.2. Use map() to create a new array, along with calling a function for each element.

8.3. Use filter() to filter the array with a function .

Reference source

Share the news now

Source : Viblo