In the last article I wrote about array destructuring in Javascript. More on this in the link bellow.
Article No Longer Available
Let's look at the syntax below. This is how we used to extract properties from obejects before ES6 was introduced. You can quickly see that the larger the object, the more repetitive code we need to write.
Now let's take the same code and destructure it following the ES6 way:
The code is much shorter, easier to read and maintain. An important note is that the variables and the properties need to have identical names, otherwise this won't work and on printing we'll get undefined.
If we must give our variables new names, we can do so by adding a colon after the initial name + the desired name. You can see this in action in the example below.
We can use the rest operator to store in a new object all the properties we didn't want in individual variables. Like so:
Using the same rest operator, we can clone objects. A very useful feature when we want to manipulate an object but we don't want to change any of the original properties. This happens to be my favorite use case for object destructuring, especially when working with React.
Top comments (2)
Is
Const {var1, var2, varX} = object
A 2015 feature?
Looks like object destructuring to me so I would say yes, it is.