# How to use object & array destructuring  in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 22, 2020, updated Dec 10, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-object-array-destructuring

> Learn how to use the ES6 destructuring expression in JavaScript to extract values from arrays or properties from objects into distinct variables. 

The destructuring assignment is a handy addition to ES6 that allows us to extract values from [arrays](https://attacomsian.com/blog/javascript-arrays), or properties from [objects](https://attacomsian.com/blog/objects-prototypes-classes-javascript#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 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:

```javascript
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:

```javascript
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 collection to a new variable:

```javascript
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 array destructuring:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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 matching names with the object's keys. This is because the object keys are in a variety of order.

Here is a basic example:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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 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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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' } }
```
