Use Array Destructuring like a PRO 😎
Tags: webdev, javascript, es6
Published: 2021-06-07 06:16:40

Hello everyone 👋,

In the previous article, we learned about  [Object Destructuring](https://dev.to/yuvgeek/use-object-destructuring-like-a-pro-4b4m) with examples. In this article, I'm going to share how to use the **Array Destructuring** effectively.

## Array Destructuring

Array destructuring helps to unpack values from an Array, assign default values to a variable & ignore elements using commas.

Let's learn each of the features with examples.

### Unpack values from an Array.

Assume, we have an array which has a list of colors code in it.

```javascript
const colorsCode = ['r', 'g', 'b'];

```
You need to create 3 variables and assign the value to them. First, let's see how to do without Array Destructuring.

```javascript
const red = colorsCode[0]; // r
const green = colorsCode[1]; // g
const blue = colorsCode[2]; // b
```
This code is perfectly fine and it will work as expected. It took 4 lines to do it. But, with Array Destructuring, it can be written in a single line as,

```javascript
const [red, green, blue] = colorsCode;
```

WOW, but what just happened?

The 1st value in the right-hand side array (`r`) is assigned to the 1st variable in the left-hand side Array declaration(`red`). Similarly, the rest of the values are assigned.


![array-dest-1(2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622986909433/RflFFgTQO.png)

The variable order should match with the value position in the Array. Let's see what happens if we change the order of the variable during the assignment.

```javascript
const [red, blue, green] = colorsCode;
console.log(red); // r
console.log(blue); // g
console.log(green); // b
```

![array-dest-2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622986968776/yK2HTfBBQ.png)

In the above example, we have swapped blue and green on the left-hand side. As we changed the variable order, `g` is assigned to `blue` and `b` is assigned to `green`. So, make sure you declare the variable name in order as per the right-hand side array value.

### Assigning Default value to a variable

You can assign a default value to the variable when the Array is empty or the value is not available.

Example 1:

```javascript
const [red, green, blue] = []
console.log(red, green, blue); // prints undefined undefined undefined

// assign default value
const [red = 'r', green = 'g', blue = 'b'] = []
console.log(red, green, blue); // prints r g b
```

Example 2:

```javascript
const [red, green, blue] = ['r', 'g']
console.log(red, green, blue); // prints r g undefined

// assign default value for a single variable
const [red, green, blue = 'b'] = ['r' ,'g']
console.log(red, green, blue); // prints r g b

```
### Ignore Array Elements

Ignoring elements with Array Destructuring can be done using `,(commas)`.

When we need only `red` & `blue` codes, it is unnecessary to declare `green` in the syntax.

```javascript
const [red, blue, green] = ['r', 'g', 'b'];
```
To avoid creating the unused variable `blue`,  replace `blue` with `,` which skips assigning the variable.

```javascript
const [red, , green] = ['r', 'g', 'b'];
```
Here is another example of ignoring elements. This creates variables only for even numbers.

```javascript
const [ ,second, ,fourth, ,sixth, ,eight] = [1, 2, 3, 4, 5, 6, 7, 8];
```

This will create only 4 variables as `second`, `fourth`, `sixth` & `eight`. It will assign the respective value to the variable based on the array order.

### Object Destructuring + Array Destructuring

Let's see the power of using Object & Array Destructuring simulatenously. (**Note**: If you haven't read my  [Object Destructuring](https://yuvaraj.hashnode.dev/use-object-destructuring-like-a-pro) article, please read it first)

```javascript
    const user = {
       firstName: 'John',
       lastName: 'Doe',
       phone: '9999999999',
       address: 'India',
       preferences: {
           mode: 'light', // light (or) dark mode
           autoSave: true,
           bookmarks: [ {name: 'bookmark 1', readCount: 10}, {name: 'bookmark 2'}]   
      }
  }
```

Our objective is to get only the `firstName`, `phone`, `address`, first bookmark `name` & the second bookmark `readCount`. If `readCount` property is not available, default value `0` to be set to it.

Without destructuring, our code could be,

```javascript
const firstName = user.firstName;
const phone = user.phone;
const address = user.address;
const firstBookmarkName = user.preferences.bookmarks[0].name;
const secondBookmarkReadCount = user.preferences.bookmarks[1]?.count || 0;
// prints John 9999999999 India bookmark 1 0
console.log(firstName, phone, address, firstBookmarkName, secondBookmarkReadCount); 
```

With destructuring, it can simplied as,

```javascript
const {
  firstName,
  phone,
  address,
  preferences: {
    bookmarks: [
      { name: firstBookmarkName },
      { count: secondBookmarkReadCount = 0 },
    ],
  },
} = user

// prints John 9999999999 India bookmark 1 0
console.log(firstName, phone, address, firstBookmarkName, secondBookmarkReadCount); 
```
Wow, isn't it wonderful? 😍

All the assignments, default values, alias are done in a single line (if not formatted). Isn't it Amazing?

Let me explain the logic behind getting the name from the first bookmark.

To get the name of the first bookmark, first, we can extract the first element from the Array using Array Destructuring.

```javascript
const { preferences: { bookmarks: [firstBookmark] } } = user; 
console.log(firstBookmark); // prints {name: 'bookmark 1', readCount: 10},
```
Then, with object destructuring, the property `name` can be unpacked from it. Also set an alias key for it.

```javascript
const { name: firstBookmarkName } = {name: 'bookmark 1', readCount: 10};
```

By merging the two things, we can simply write it as,

```javascript
const { preferences: { bookmarks: [{ name: firstBookmarkName }] } } = user; 

```
Similarly, `readCount` can be fetched with Array destructuring first and then applying Object destructuring.

Yay! It's simplified and much readable with Modern JavaScript. Thanks to Array & Object Destructuring. 😍🎉

**BONUS:**

You can do array destructuring with Strings as well.

```javascript
 const [d, e, v] = 'DEV';
console.log(d, e, v); // D E V
```

Thanks for reading my article. If you like my article, please share it with your friends!