Spread operator VS Array Destructuring: Key Difference
Understanding ES6: Concept of desturcturing
In this article, I will be explaining a feature of ES6: Destructuring, as well as the key difference between the spread operator and array destructuring for a better understanding.
The spread syntax copies all contents of an array into a comma-separated list. Here is a demonstration:
const myPreference = {
brand: 'Mercedes',
model: 'GLK',
color: 'Ash'
}
const updateMyPreference = {
type: 'car',
year: 2022,
color: 'red'
}
const myUpdatedPreference = {...myPreference, ...updateMyPreference}
//Check the result object in the console:
console.log(myUpdatedPreference);
// expected output:
// Object { brand: "Mercedes", model: "GLK", color: "red", type: "car", year: 2022 }
In the example above, you cannot choose which elements you would like to assign to a variable. ES6 fixes that! It's introduced feature makes destructuring arrays as simplified as destructuring objects.
Here is a demonstration:
const [newVarOne, newVarTwo] = ["elementOne", "elementTwo", "elementThree", "elementFour"];
console.log(newVarOne, newVarTwo);
// expected output: newVarOne is elementOne and newVarTwo is elementTwo
In the example above, we were able to assign variables to elements in the array with the help of destructuring in ES6.
The variable newVarOne
, is assigned the first value of the array, and newVarTwo
, is assigned the second value of the array. You can even access the value at any index in an array by using commas to reach the index of your chioce. See a demonstration below:
const [newVarOne,, newVarTwo] = ["elementOne", "elementTwo", "elementThree", "elementFour"];
console.log(newVarOne, newVarTwo);
// expected output: newVarOne is elementOne and newVarTwo is elementThree
Notice the difference. The assigned variable newVarTwo
was moved two places, that is, it skipped the second and moved to the third element in the array, due to the commas. You can play around the code to enlighten your understanding more on the concept of destructuring in ES6. You can also visit the MDN documentation for further explanations.
I hope this article helped your understanding more in ES6 destructuring.
Make sure to leave a comment on the article and share your knowledge as well.
See you in the next article.