Destructuring must be my favorite feature of ECMAScript 6. I don’t exactly know why, I guess I just like the simplicity. It makes your code more clean and declarative.
What destructuring does is it can extract seperate variables from an object or array. I guess you would like to see some code by now, let’s say we have the following object:
We can now ‘destructure’ it like this:
You can also specify new variable names:
Arrays work the same, except the output is controlled by the order of the array, instead of the key names:
The array version is only useful if you know the order of the array, it can for instance be useful if you have a function that returns something like an array of coordinates:
There are two big advantages of using destructuring. The first one is that your code more readable. If you destructure an object at the top of a function or code block, it is clear to the reader what variables you are going to use.
The second plus is performance. Destructuring encourages programmers to put object properties in local variables before using them, which can improve application performance. Especially if you are accessing those variables multiple times, maybe in a loop, it is more efficiënt if the variables are locally defined.
You see me using const instead of var a lot in this article. This is a new ECMAScript 6 feature which I will cover in a later article.
Personally I use destructuring a lot when accessing the props or state object in React. A render function without destructuring:
At first sight the second method does not seem more efficient. But it declares what props are going to be used, the code is more readable and in larger render functions the advantages will become more evident. If you are coding ES6 in your project, try destructuring out!