Destructuring in javascript is an expression that makes it possible to select values as variables from arrays or objects.
Let’s start with an example:
let [a, b] = [1, 2];
console.log(a, b); //will log 1 and 2
[a, ...rest] = [3, 4, {}];
console.log(a, rest); //will log 1 and [4, [object Object]]
As you can see above let [a, b] = [1, 2];
will initialize two variables with values 1 and 2 respectively by destructuring that array into a and b variables.
Example 2:
Using default values:
const [a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
Here, a
will have value 1 as the only element in the array is 1 and b
will take the value 7 because that will be the default that we have set using the assignment operator.
The same rules apply also to object destructuring.
Example:
const person = {firstName: 'Daniel', lastName:'Popa'};
const {firstName, lastName} = person;
console.log(firstName); // Daniel
console.log(lastName); // Popa
Until now, everything looks the same as at array destructuring.
const person = {firstName: 'Daniel', lastName:'Popa', address: {
street: 'Street'
}};
const {firstName, lastName, address: { street } } = person;
console.log(firstName); // Daniel
console.log(lastName); // Popa
console.log(street); // Street
In the last example there are some new things as { address: { street } }
. When you have nested objects and you want to destructure properties that lies inside of them then this is the syntax you need.
You can also read more about it here.
That’s really all you have to know about javascript destructuring in order to be productive.