What is destructuring in JavaScript?

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.

Destructuring arrays

Let’s see how destructuring works on arrays.

fruits = ["Apple","Banana","Melon","Plum"] //Array to be destructured
var [fruit1, fruit2] = fruits //Destructuring
console.log(fruit1)
console.log(fruit2)
This is what happened in the code above
This is what happened in the code above

Let’s now see a few techniques to use destructuring efficiently:

Example1 of code above
Example1 of code above
Example2 of code above
Example2 of code above

Destructuring objects

Destructuring objects is slightly different from destructuring arrays.

var car = {
category : "sports",
color : "red",
top_speed : 240
} //object to be destructured
var {top_speed, color} = car //
console.log(top_speed)
Copyright ©2024 Educative, Inc. All rights reserved