Javascript - Operator Destructuring Assignment

Introduction

Destructuring can also be used in assignment statements.

Consider the following example,

function getChars(){
    return ["a","b","c"];
}

function getNumbers(){
    return {a:1,b:2,c:3};
}

var a, b, c, x, y, z; 

[x, y ,z] = getChars(); 
( { a, b, c } = getNumbers() ); 

console.log( x, y, z );             // a b c 
console.log( a, b, c );             // 1 2 3 

In this example the x, y, z, a, b, and c are all assigned using destructuring after they are declared.

You must always use parentheses around an object destructuring assignment statement.

You can also change the values of variables after they are assigned using destructuring.

let item = { 
        name: "Tom", 
        quantity: 5 
    }, 
    name = "Jack", 
    quantity = 3; 

// assigning different values using destructuring 
({ name, quantity } = item); 

console.log(name);          // "Tom" 
console.log(quantity);      // 5 

Here, name, quantity, and item are initialized with values in a single declaration statement.

Then name and quantity are assigned new values by fetching values from item using destructuring.

Related Topic