Learn about Destructuring in ES6

Tram Ho

Hello friends! Although javascript ES6 was introduced a long time ago, but I have not really understood and proficiently used the introduced features. Recently, I have learned and used a feature that I think is quite good and useful when we work with array or object literial, that is Destructuring. In this article I will introduce destructuring and the cases that need to use it.

Destructuring

Destructuring is an easy feature, simple and I use the most. The great thing is that this feature works with both arrays and objects in javascript.

Destructuring allows us to retrieve a specific property very quickly.

In addition, we can also name our variables with syntax.

They can also take properties deep inside an object and can also name properties deep inside them.

By default, if the property is not found in the object, it will have the value undefined, just like when we try to get the value of a property that is not in the object.

If we try to get the value of a property deep inside that doesn’t exist in the object, an exception will be thrown.

One of my favorite applications of destructuring is swapping values ​​between two variables.

We can also use ‘computed property names’ in destructuring.

We can also assign a default value to a variable when that variable is undefined.

As mentioned above, destructuring also works with arrays, now we replace the {and} signs with [and] signs.

Cases of using Destructuring

Following are some cases where destructuring will be helpful. When a function returns an object, then you want to attach the propery in that object to separate variables, destructuring will help you do that very simply.

Use destructuring in the function param

Above I introduced the syntax, the case should use destructuring. I hope my article will help you understand destructuring and use this feature in your code.

Share the news now

Source : Viblo