Yuvaraj's Blog


Yuvaraj's Blog

Use Array Destructuring like a PRO ๐Ÿ˜Ž

Use Array Destructuring like a PRO ๐Ÿ˜Ž

Yuvaraj's photo
ยทJun 6, 2021ยท

5 min read

Hello everyone ๐Ÿ‘‹,

In the previous article, we learned about Object Destructuring 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.

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.

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,

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.


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.

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


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:

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:

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.

const [red, green, blue] = ['r', 'g', 'b'];

To avoid creating the unused variable green, replace green with , which skips assigning the value to the variable.

const [red, , blue] = ['r', 'g', 'b'];

Here is another example of ignoring elements. This creates variables only for even numbers.

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 article, please read it first)

    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,

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,

const {
  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.

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.

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

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

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. ๐Ÿ˜๐ŸŽ‰


You can do array destructuring with Strings as well.

 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!

Did you find this article valuable?

Support Yuvaraj by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this