Destructuring assignment in javascript

Destructuring assignment in javascript

What does destructuring mean?

It is a Javascript syntax which help us to extract data from the arrays, objects, maps and sets. It allows to get the properties of object or array items, multiple at a time.

Let’s look what we can do with the object destructuring and which problems it really solves.

const family = {
    father: "Name of the father",
    mother: "Name of the mother",
    sister: "Name of the sister"

Without destructuring if you want to get the details of the family in separate variables then you need to do as below:

const father = family.father;
const mother = family.mother;
const sister = family.sister;

Now, let’s get them with the destructuring syntax:

const { father, mother, sister } = family;

Now, you can see how the code becomes more readable and of course pretty.
Let’s understand the above code that how it will work. The above code will get the father, mother and sister property from the object called family.
We can do many more with the destructuring syntax in javascript. Let’s check some examples which are widely used.

1. You can destructure from an array

let [x, y] = ['value1', 'value2'];

console.log(x); // Will output 'value1'
console.log(y); // Will output 'value2'

2. You can destructure from an object

let { x, y } = { x: 10, y: 20 };

console.log(x); // Will output 10
console.log(y); // Will output 20

3. You can alias the distinct variables according to your need

let { x: a, y: b } = { x: 10, y: 20 };

console.log(x); // Will output 10
console.log(y); // Will output 20

4. You can assign default value to the distinct variable if your object does not have

let { x: a = 15, y: b } = { y: 20 };

console.log(x); // Will output 15
console.log(y); // Will output 20

5. You can ignore values from an array if you don't want

let [a, , c] = [4, 5, 6];

console.log(a); // Will output 4
console.log(c); // Will output 6

6. You can assign rest of an array/object to a variable

let [a, b,] = [4, 5, 6, 7, 8, 9];

console.log(a); // Will output 4
console.log(b); // Will output 5
console.log(rest); // Will output [6, 7, 8, 9]


So, we can say that using the object destructuring syntax of the javascript you can easily make your code more readable and also can decrease the number of lines.