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.
Level up every day