Skip to content

JavaScript destructuring Assignment

  • by

JavaScript destructuring Assignment makes it easy to assign array values and object properties to distinct variables. It is introduced in ES6.

Destructing Arrays

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car, truck, suv] = vehicles;

It possible to unpack values from arrays, or properties from objects, into distinct variables.

Note: Object destructuring assigns the properties of an object to variables with the same names by default.

JavaScript destructuring

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
   // assigning object attributes to variables
   const person = {
    name: 'John',
    age: 25,
    gender: 'Male'    
  }

    // destructuring assignment
    let { name, age, gender } = person;

    console.log(name); 
    console.log(age); 
    console.log(gender); 
  </script>
</body>
</html>

Output:

JavaScript destructuring Assignment

You can also perform array destructuring in a similar way. For example,

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

// destructuring assignment in arrays
const [x, y, z] = arrValue;

console.log(x); // one
console.log(y); // two
console.log(z); // three

Nested object destructuring

Assuming that you have an employee an object which has a name object as the property:

let employee = {
    id: 1001,
    name: {
        firstName: 'John',
        lastName: 'Doe'
    }
};Code language: JavaScript (javascript)

The following statement destructures the properties of the nested name object into individual variables:

let {
    name: {
        firstName,
        lastName
    }
} = employee;

console.log(firstName); // John
console.log(lastName); // Doe

It’s possible to do multiple assignments of a property to multiple variables:

let employee = {
    id: 1001,
    name: {
        firstName: 'John',
        lastName: 'Doe'
    }
};

let {
    name: {
        firstName,
        lastName
    },
    name
} = employee;

console.log(firstName); // John
console.log(lastName); // Doe
console.log(name); // { firstName: 'John', lastName: 'Doe' }

Destructuring function arguments

Suppose you have a function that displays the person object:

let display = (person) => console.log(`${person.firstName} ${person.lastName}`);

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

display(person);Code language: JavaScript (javascript)

It’s possible to destructure the object argument passed into the function like this:

let display = ({firstName, lastName}) => console.log(`${firstName} ${lastName}`);

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

display(person);

Do comment if you have any doubts or suggestions on this Js topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *