DEV Community

Cover image for Use Array Destructuring like a PRO 😎
Yuvaraj
Yuvaraj

Posted on

Use Array Destructuring like a PRO 😎

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'];

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

array-dest-2.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:

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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, blue, green] = ['r', 'g', 'b'];
Enter fullscreen mode Exit fullscreen mode

To avoid creating the unused variable blue, replace blue with , which skips assigning the variable.

const [red, , green] = ['r', 'g', 'b'];
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode

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'}]   
      }
  }
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

With destructuring, it can simplied as,

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); 
Enter fullscreen mode Exit fullscreen mode

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},
Enter fullscreen mode Exit fullscreen mode

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};
Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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.

 const [d, e, v] = 'DEV';
console.log(d, e, v); // D E V
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)