Let’s Destructure!

Dhruv Sharma
2 min readJan 26, 2021

What does destructuring mean?

Well, the literal meaning is to destroy the structure of something or for simplicity, we can say modify the structure of something.

Now, coming back to JavaScript and JS destructuring assignment.

Destructuring Assignment

According to MDN, The destructuring assignment syntax is a javascript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Let’s simplify it a bit, destructuring assignment allows a programmer to assign properties of an array to a bunch of variables. Let’s take an example.

let a, b, c;[a, b] = [10, 20];console.log(a); // 10console.log(b); // 20 [a, b, ...c] = [10, 20, 30, 40, 50];console.log(c); // [30, 40, 50] 

Swapping Variables

Variable swapping is one of my favorite parts of destructuring, Two variables can be swapped in one single expression, Let us see how.

let a = 5;
let b = 10;
[a, b] = [b, a]console.log(a)
// 10
console.log(b)
//5

Object Destructuring

Object destructuring helps you bind variables to different properties of an object. first, we specify the property being bound, followed by the variable we are binding its value to.

var dog_1 = {name: "dexter"};
var dog_2 = {name: "lexi"};
var {name: name_dog_1} = dog_1;
var {name: name_dog_2} = dog_2;
console.log(name_dog_1);
// "dexter"
console.log(name_dog_2);
//lexi

Destructuring values that are not an object, array, or iterable like null or NaN throws a Type error and for other primitive types such as boolean, numbers, and strings, we get undefined.

We can say that destructuring is useful in many individual small cases as well as for bigger projects, This was just a basic and small post on the explanation and use of destructuring, for further and deep knowledge of the topic please refer to the footnotes.

--

--