Destructuring is a feature introduced with ES6. A feature that enables you to break down a structure, like an array or object, and store its components in variables.
Let’s see how destructuring works on arrays.
fruits = ["Apple","Banana","Melon","Plum"] //Array to be destructuredvar [fruit1, fruit2] = fruits //Destructuringconsole.log(fruit1)console.log(fruit2)
Let’s now see a few techniques to use destructuring efficiently:
fruits = ["Apple","Banana","Melon","Plum"] //Array to be destructuredvar [,fruit1,, fruit2] = fruits //Focus on the use of extra commas to skip through elementsconsole.log(fruit1)console.log(fruit2)
Destructuring objects is slightly different from destructuring arrays.
var car = {category : "sports",color : "red",top_speed : 240} //object to be destructuredvar {top_speed, color} = car //console.log(top_speed)
Free Resources