Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

destructuring
javascript

What is destructuring in JavaScript?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Note that it's the sequence of variables that determines which element corresponds to which variable.
svg viewer
This is what happened in the code above

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

fruits = ["Apple","Banana","Melon","Plum"] //Array to be destructured
var [,fruit1,, fruit2] = fruits //Focus on the use of extra commas to skip through elements
console.log(fruit1)
console.log(fruit2)
Selecting desired elements
svg viewer
Example1 of code above
svg viewer
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)
Note that it's the name of the variable, rather than the sequence, that's important

RELATED TAGS

destructuring
javascript
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring