Destructuring in ES6
This is a short guide for using destructuring in Array and Objects.
Destructuring Objects
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It is special syntax introduced in ES6, for neatly assigning values taken directly from an object.
Consider the following ES5 code:
const user = { name: 'John Doe', age: 34 };
const name = user.name;
const age = user.age;
In the above code name would have a value of the string John Doe
, and age would have the number 34
.
Here's an equivalent assignment statement using the ES6 destructuring syntax:
const { name, age } = user;
Again, name would have a value of the string John Doe
, and age would have the number 34
.
Here, the name and age variables will be created and assigned the values of their respective values from the user object. You can see how much cleaner this is.
You can extract as many or few values from the object as you want.
Use Destructuring Assignment to Assign Variables from Objects
Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value. Here's how you can give new variable names in the assignment:
const user = { name: 'John Doe', age: 34 };
const { name: userName, age: userAge } = user;
You may read it as "get the value of user.name and assign it to a new variable named userName" and so on. The value of userName
would be the string John Doe
, and the value of userAge
would be the number 34
.
Use Destructuring Assignment to Assign Variables from Nested Objects
You can use the same principles to destructure values from nested objects. Using an object similar to previous examples:
const user = {
johnDoe: {
age: 34,
email: 'johnDoe@freeCodeCamp.com'
}
};
Here's how to extract the values of object properties and assign them to variables with the same name:
const { johnDoe: { age, email }} = user;
You can also assign an object properties' values to variables with different names:
const { johnDoe: { age: userAge, email: userEmail }} = user;
Destructuring Arrays
Use Destructuring Assignment to Assign Variables from Arrays
Destructuring arrays is as easy as destructuring objects. It seems to be very similar to spread operator but a key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables whereas destructuring an array lets us do exactly that.
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a);
// will print 1
console.log(b);
// will print 2
The variable a
is assigned the first value of the array, and b
is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index:
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a);
// will print 1
console.log(b);
// will print 2
console.log(c);
// will print 5
You can also swap values of variables using array destructuring
let a = 8, b = 6;
[a,b] = [b,a]
Here the value a
will be 6
while that of b
will be 8
. Make sure you don't redeclare variables a
and b
using let
else it will throw an error.
Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements
In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array. The result is similar to Array.prototype.slice(), as shown below:
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a);
// will print 1
console.log(b);
// will print 2
console.log(arr);
// will print [3, 4, 5, 7]
Variables a
and b
take the first and second values from the array. After that, because of the rest parameter's presence, arr
gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out the last element of the original array.
Use Destructuring Assignment to Pass an Object as a Function's Parameters
In some cases, you can destructure the object in a function argument itself. Consider the code below:
const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
}
This effectively destructures the object sent into the function. This can also be done in-place:
const profileUpdate = ({ name, age, nationality, location }) => {
// some code
}
When profileData is passed to the above function, the values are destructured from the function parameter for use within the function.
Read more about Destructuring Assignment in MDN docs