Destructuring assignment – The Modern JavaScript Tutorial

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into a distinct variable.
In ES5, we had to use the below approach.
        
const person = {
    name: 'ankit',
    age: 30,
}

let name = person.name;
let age = person.age;

console.log(name);        // Output : Sara
console.log(age);         // Output : 25        
    
In ES6, we had to use the below approach.
        
const person = {
    name: 'ankit',
    age: 30,
}

let { name, age, gender } = person;

console.log(name);       //Output :  Sara
console.log(age);        // Output : 25        
    

There are two types of destructuring assignment expressions, namely, Array Destructuring and Object Destructuring. It can be used in the following mannerĀ 

Array Destructuring

You can also perform array destructuring in a similar way

        
const array = ['one', 'two', 'three'];

//destructuring assignment in arrays

const [a, b, c] = array;
console.log(a);         // Output : one
console.log(b);         // Output : two
console.log(c);         // Output : three        
    
Object Destructuring

You can also perform object destructuring in a similar way

 

        
let person = {name: "Ankit", age: 30};
let {name, age} = person; 

console.log(name);      //Output : Ankit        
    
Swapping Variables

In this example, two variables are swapped using the destructuring assignment syntax.

        
let a = 3;
let b = 5;
[a, b] = [b, a];

console.log(a);     // Output : 5
console.log(b);     // Output : 3         
    
Skip Items

You can skip unwanted items in an array without assigning them to local variables.

        
const array = ['one', 'two', 'three'];
        
// destructuring assignment in arrays

const [a, , c] = array;
console.log(a);         // Output : one
console.log(c);         // Output : three        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top