Destructuring Assignment in JavaScript

·

2 min read

Destructuring Assignment in JavaScript

Table of contents

No heading

No headings in the article.

Have been learning Javascript lately, and coming across various use cases which proves to be handy and efficient at the same time. One such is the topic of Destructuring Assignments that I came across.

So what is Destructuring Assignment you ask ?

if you are into programming, you have used the assignment operator which helps us to assign values to a variable. For example :

let x = 5;  // here the value 5 is assigned to the variable x.

Similarly, if we talk of an array, we can obtain the first five elements in an array as follows :

let a = myArray[0];  // assigns element in 0th index to variable a        
let b = myArray[1];  // assigns element in 1st index to variable b
let c = myArray[2];  // assigns element in 2nd index to variable c
let d = myArray[3];  // assigns element in 3rd index to variable d
let e = myArray[4];  // assigns element in 4th index to variable e

But if we apply destructuring assignment to this situation, the above code could be broken down to one single line as follows :

let [a, b, c, d, e] = myArray;  // assigns elements in myArray to the variables a to e.

The same strategy can also be applied to objects. Yes, you got it right. We can also use the destructuring assignments on objects too. Just see the below code as example :

let { fname, lname } = { fname : "Jyotirmoy" lname : "Das" };

In NodeJS based projects you might come across code such as the following :

const { username, email, password } = req.body;

So here essentially we are destructuring all the three object values (obtained from the body) in one single line.

Hope this article helps !!