The destructuring assignment is a very useful addition to ES6 that allows us to extract values from arrays, or properties from objects, into a bunch of distinct variables. It is a special syntax that unpacks arrays and objects into multiple variables.

Destructuring is extremely useful when you don't want to pass the object or the array to a function as a whole, but rather as individual pieces. Let us see how it is done in the following examples.

Array Destructuring

The array destructuring syntax automatically creates variables with the values from the corresponding items in an array:

const fruits = ['Apple', 'Mango', 'Cherry'];

const [apple, mango, cherry] = fruits;

console.log(apple);     // Apple
console.log(mango);     // Mango
console.log(cherry);    // Cherry

Skipping values

The unwanted items of the array can be skipped by using an extra comma and leaving the variable names empty:

const fruits = ['Apple', 'Mango', 'Cherry'];

const [apple, , cherry] = fruits;

console.log(apple);     // Apple
console.log(cherry);    // Cherry

Destructuring a part of the array

You can even choose to destructure a part of the array, and assign the rest of the array to a new variable:

const fruits = ['Apple', 'Mango', 'Cherry'];

const [apple, ...remaining] = fruits;

console.log(apple);        // Apple
console.log(remaining);    // ['Mango', 'Cherry']

Assigning values to an object

What if you want to assign the array's values to an object? You can easily do it with the array destructuring:

let user = {};

[user.name, user.age] = ['John Doe', 29];

console.log(user.name);     // John Doe
console.log(user.age);      // 29

Default values

If there are fewer values in the array than variables specified in the assignment, there won't be any error. Destructuring automatically assigns default values to extra variables:

const [name, age] = ['Atta'];

console.log(name);      // Atta
console.log(age);     // undefined

You can also define your own default values for variables in the assignment:

const [name = 'John Doe', age = 30] = ['Atta'];

console.log(name);      // Atta
console.log(age);       // 30

The age property falls back to 30 because it is not defined in the array.

Swapping variables

The destructuring assignment can also be used to swap the values of two variables:

let a = 15;
let b = 5;

[a, b] = [b, a];

console.log(a);     // 5
console.log(b);     // 15

Object Destructuring

The destructuring assignment also works with JavaScript objects. However, the assignment variables must have the matching names with the object's keys. This is because the object keys are not necessarily in a particular order.

Here is an a basic example:

const animals = { cat: '🐱', monkey: '🐒', whale: '🐋' };

const { cat, whale, monkey } = animals;

console.log(cat);       // 🐱
console.log(whale);     // 🐋
console.log(monkey);    // 🐒

Using a new variable name

If you want to assign values of an object to new keys instead of using the name of the existing object keys, you can do the following:

const animals = { cat: '🐱', monkey: '🐒', whale: '🐋' };

const { cat: newCat, whale: newWhale, monkey: newMonkey } = animals;

console.log(newCat);       // 🐱
console.log(newWhale);     // 🐋
console.log(newMonkey);    // 🐒

Default values

Just like array destructuring, the default values can also be used in object destructuring:

const animals = { cat: '🐱', monkey: '🐒', whale: '🐋' };

const { cat, sheep = '🐑', lion } = animals;

console.log(cat);       // 🐱
console.log(sheep);     // 🐑
console.log(lion);      // undefined

You can also set default values when you assign value to a new variable:

const animals = { cat: '🐱', monkey: '🐒', whale: '🐋' };

const { cat, sheep: wool = '🐑'} = animals;

console.log(cat);       // 🐱
console.log(wool);      // 🐑

Computed property name

The computed property name is another ES6 feature that also works for object destructuring. It allows the names of the object properties in JavaScript object literal notation to be computed dynamically.

Here is an example that computes the name of the object property by using "Computed Property Name" notation:

const animals = { cat: '🐱', monkey: '🐒', whale: '🐋' };

const prop = 'monkey';

const { [prop]: newMonkey } = animals;

console.log(newMonkey);     // 🐒

Extracting arrays from the object

The object destructuring also works for the arrays present inside the object as values:

const user = { name: 'Atta', friends: ['Ali', 'Amir'] };

const { name, friends } = user;

console.log(name);      // Atta
console.log(friends);   // ['Ali', 'Amir']

Nested objects destructuring

The object may contain nested objects when destructuring. You have to define the same nesting structure at the left side of the assignment to extract values from deeper objects:

const user = {
    name: 'Atta',
    place: {
        city: 'Sahiwal',
        country: 'Pakistan'
    }
};

const { name, place: { city, country } } = user;

console.log(name);      // Atta
console.log(city);      // Sahiwal
console.log(country);   // Pakistan

All properties of the user object are assigned to variables in the assignment. Finally, we have name, city, and country distinct variables. Note that there is no variable for place as we only extracted its content.

Destructuring a part of the object

Just like arrays, you can also destructure a part of the object and assign the rest of the object to a new variable:

const user = {
    name: 'Atta',
    place: {
        city: 'Sahiwal',
        country: 'Pakistan'
    }
};

const { name, ...location } = user;

console.log(name);
// Atta

console.log(location);
// { place: { city: 'Sahiwal', country: 'Pakistan' } }

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: