Destructuring assignment feature provides an easy, readable way to handle object and array assignments.
ES6 introduced assignment destructuring, which provides a clean and more readable way to assign variables.
The old way -
1
2
3
4
|
const fruits = { apple: { color: "red" }, orange: { color: "orange" } };
const appleTheFruit = fruits["apple"];
console.log("color of apple: ", appleTheFruit.color); // red
|
The new way..
1
2
3
4
5
|
const fruits = { apple: { color: "red" }, orange: { color: "orange" } };
const { apple } = fruits;
// or also include orange: const { apple, orange } = fruits;
console.log("color of apple: ", apple.color); // red
|
The new syntax gives us a quick and easy way to get named props within an object.
Same can be applied to an array as well.
1
2
3
4
5
6
7
8
9
|
const planets = [
{ name: "mercury", position: 1 },
{ name: "venus", position: 2 },
{ name: "earth", position: 3 }
];
let [quickestPlanet, , thirdPlanetFromSun] = planets;
console.log("quickestPlanet: ", quickestPlanet); // { name: 'mercury', position: 1 }
console.log("thirdPlanetFromSun: ", thirdPlanetFromSun); // { name: 'earth', position: 3 }
|
A Practical Example
Let us see an example of where destructuring can really help/
What do you do when are want to pass arguments to functions? Previously -
1
2
3
4
5
6
|
function getSum(a, b) {
return a.value + b.value;
}
const sum = getSum({ name: "num1", value: 3 }, { name: "num2", value: 2 });
console.log("sum: ", sum); // 5
|
Passing multiple arguments may lead to confusion and future maintenance issues. We tend to pass one parameter when feasible.
1
2
3
4
5
6
7
8
9
10
11
|
function getSum(nums) {
let x = nums["a"].value;
let y = nums["b"].value;
return x + y; // 5
}
const sum = getSum({
a: { name: "num1", value: 3 },
b: { name: "num2", value: 2 }
});
console.log("sum: ", sum); // 5
|
With ES6 assignment destructuring, we can now make this simpler to read.
1
2
3
4
5
6
7
8
9
10
|
function getSum(nums) {
let { a, b } = nums;
return a.value + b.value; // 5
}
const sum = getSum({
a: { name: "num1", value: 3 },
b: { name: "num2", value: 2 }
});
console.log("sum: ", sum); // 5
|
Arrays
Concepts described above are applicable for array destructuring.
1
2
3
|
const [x, y] = [1, 2];
console.log(x); // 1
console.log(y); // 2
|
We can do partial assignments as well..
1
2
3
|
const [x, y] = [1, 2, 3, 4, 5];
console.log(x); // 1
console.log(y); // 2
|
Another way of looking at the same solution..
1
2
3
4
5
|
const nums = [1, 2, 3, 4, 5];
[x, y] = [...nums];
console.log(x); // 1
console.log(y); // 2
|