DEV Community

Cover image for Destructuring in Javascript
Sayantani96
Sayantani96

Posted on

Destructuring in Javascript

Overview

Destructuring is one of the coolest features introduced in ES6. The destructure feature allows us to break an object or an array into its values. Then we can access the values just by using the separate variables. It becomes easy to access the array and object elements in this way.

const arr=[5,8,10,67,34];

const [first,second]=arr

const obj={

name: "Titli",

id:1

}

const {name,id}=obj;
Enter fullscreen mode Exit fullscreen mode

Object Destructuring

We use keys as the name of variables for destructuring objects. The variable names should be the same as the keys of the object, otherwise undefined will be returned. Unlike array destructuring, objects identify values by their properties(keys) instead of index.

const obj={
    id:1,
    name:"Shanaya",
    email:"shanaya23@gmail.com",
}

const {id,name,email}=obj;
console.log(id,name); // 1 Shanaya
Enter fullscreen mode Exit fullscreen mode

We can also destructure objects when it's nested.

const obj={
    id:1,
    name:"Shanaya",
    email:"shanaya23@gmail.com",
    mentee:{
        id:3,
        name:"Subhojit",
        email:"subh89@gmail.com"
    }
}

const {mentee:{name:menteeName}}=obj;
console.log(menteeName); // Subhojit
Enter fullscreen mode Exit fullscreen mode

From the above example, we see how we can access a value from a nested object through destructuring. We access the value of name of the mentee which is an object nested inside object obj.

We also see how we can assign a new variable name to the value and access the value using that name. Instead of using the name key we assign value of name inside mentee to a new variable called "menteeName" and then access the value using "menteeName".

Array Destructuring

While destructuring an array, we separate the values using their index. For example,

const arr=[1,8,3,6,9];

const [first, second]=arr;

console.log(first,second);// 1 8
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, we see how the first variable points to the first element in the array (arr[0]) and the second variable to the second element in the array (arr[1]). The destructured variables points to the values in the positions they are placed.

const arr=[1,8,3,6,9];

const [third,second,first,fourth,eighth]=arr;

console.log(first,second,third,eighth); // 3 8 1 9
Enter fullscreen mode Exit fullscreen mode

As we see in the above example, we have given random names to the variables to access the array elements. The variables point to the values according to their index. For example, first points to arr[2] as the variable named first is at index number 2. Similarly, third points to arr[0] as it is positioned at index 0.

Now, the next big question is: what if we want to access a value in an array by skipping the initial values? We can do that too.

const arr=[1,8,3,6,9];

const [,,third,,fifth]=arr;

console.log(third,fifth); // 3 9
Enter fullscreen mode Exit fullscreen mode

From the above example, we see how we can access the values of a specific index through destructuring.

There is another way to do this.

const arr=[1,8,3,6,9];

const {2:third,4:nine}=arr;

console.log(third,nine); // 3 9
Enter fullscreen mode Exit fullscreen mode

As we know arrays in javascript are special objects. The index values in arrays act as the keys or properties. We use this knowledge to destructure arrays more cleanly. We assign a new variable name to the array elements at the specified index and access the values using those variable names.

Coming to nested destructuring of arrays, it's pretty easy. Let's see an example.

onst arr=[1,8,[3,6,8,16],9];

const {2:[first,second]}=arr;

console.log(first,second); // 3 6
Enter fullscreen mode Exit fullscreen mode

As we see, we can destructure a nested array in a similar manner. Now that we have seen almost all the possible ways of destructuring, I would like to end this blog with an example which has mixture of all the cases.

const book = { 
        title: 'A Definitive Guide to Javascript',  
        authors: [{name: 'D. Flanagan', age: 49 }, { name: 'Y. Matsumoto', age: 57 }],  
        publisher: {name: 'O\'Reilly Media', location: 'LA'}
};


const {title,authors:[{name:author1},{name:author2}],publisher:{name:publisherName}}=book;


console.log(title); // A Definitive Guide to Javascript
console.log(author1); // D. Flanagan 
console.log(author2); // Y. Matsumoto
console.log(publisherName); // O'Reilly Media
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
const str = "Hello world!"
const {length, [length-1]: last} = str

console.log(length)  // 12
console.log(last)  // '!' 
Enter fullscreen mode Exit fullscreen mode