Thought leadership from the most innovative tech companies, all in one place.

Array Destructuring in JavaScript: A Comprehensive Beginner's Guide

image

According to the official MDN documentation, the destructuring assignment syntax* “is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.”*

Before we delve into the examples, let's understand how array destructuring works conceptually.

Destructuring is an ECMAScript 6 (ES6/ECMAScript 2015) feature. When it comes to arrays, destructuring is basically a way to unpack values from an array into separate variables. In other words, destructuring is all about breaking a complex data structure (an array in this case) down into a smaller (and therefore simpler) data structure, like a variable.

For arrays, the primary benefit of destructuring is that we can retrieve elements from the array and store them into variables in a very easy way. Let's start with a very simple array and use destructuring to extract elements from it.

Extracting Elements

let arr = ["Soumadri", "Sunil", "John"];

And now, here's how we would retrieve each element traditionally.

let name1 = arr[0];

let name2 = arr[1];

let name3 = arr[2];

console.log(name1, name2, name3);

Which would give us the following output:

image

Now, let's see how we'd do the same thing using destructuring. To destructure an array, we use a ‘[]' on the left-hand side of the assignment operator. Whenever JavaScript sees this, it will know that it needs to perform destructuring.

And now, using destructuring, we can declare all three variables at the same time. Let's see how we'll do it:

let [name1, name2, name3] = arr;

That's it. And now let's check the result in the console.

console.log(name1, name2, name3);

image

And indeed, as we can see, our code produces the exact same result but with a single line of code.

We can also see that the original array remains unaffected.

console.log(arr);

image

Extracting Selected Elements

We also do not have to take all of the elements out of the array. Let's check out an example where we perform destructuring to retrieve selected elements from an array. We'll be using the arr array once again.

let arr = ["Soumadri", "Sunil", "John"];

let [name1, , name2] = arr;

The double commas between name1 and name2 ensure that the element at the corresponding index position is skipped. So name1 retrieves the element at the 0th index (“Soumadri”) and name2 retrieves the element at the 2nd index (“John”) while the element in between, the one at** the 1st index position (“Sunil”) is skipped.**

Let's see the result.

console.log(name1, name2);

image

And indeed, we get Soumadri and John as expected.

Swapping Variables

Let's see how we can swap variables using destructuring. Let's declare two variables name1 and name2, and assign them some values.

let name1 = "Sunil";

let name2 = "Soumadri";

Traditionally, this is how we'd perform swapping.

let tmp = name1;

name1 = name2;

name2 = tmp;

console.log(name1, name2);

image

Now, with destructuring, we can do this in a single line. Reset the values of name1 and name2 in case you're using the same file and/or don't have the above code commented out.

let name1 = "Sunil";

let name2 = "Soumadri";

[name2, name1] = [name1, name2];

And now let's check the result.

console.log(name1, name2);

image

And indeed, we get the swapped values of name1 and name2.

So, let's try out these techniques on some of the arrays present in the library object below (feel free to create one with values of your own). This will help give you a brief idea of how destructuring works in real-life applications.

Destructuring Array Values from an Object

First things first, let us create our library object.

const library = {
  name: "Soumadri's Fiction Book Shelf",

  location: "1234 Fiction Palace, Calcutta, India",

  genres: [
    "Mystery",

    "Horror",

    "Fantasy",

    "Sci-Fi",

    "Literary Fiction",

    "Historical Fiction",
  ],

  titles: [
    "The Inugami Clan",

    "The Three Coffins",

    "In Search of Lost Time",

    "Sandman",

    "The Left Hand of Darkness",

    "The Complete Works of H.P. Lovecraft",

    "Do Androids Dream of Electric Sheep?",

    "In the Woods",

    "In a Glass Darkly",

    "Fingersmith",
  ],

  authors: [
    "Neil Gaiman",

    "Ursula Le Guin",

    "Sheridan Le Fanu",

    "H.P. Lovecraft",

    "Marcel Proust",

    "Tana French",

    "John Dickson Carr",

    "Seishi Yokomizo",

    "Philip K. Dick",

    "Sarah Waters",
  ],
};

Please don't be intimidated by the size of the object if you're a beginner. I'll briefly explain the keys and values.

  • name: Name of my personal bookshelf/library.

  • address: Address of the library.

  • genres: An array storing all the genres of books present in the library.

  • titles: An array storing all the names of the books present in the library.

  • authors: An array storing all the names of the authors whose books are present in the library.

Now, let's say we only want to retrieve the first and second elements (that is the names of two books) from the library.titles array. Therefore, this is the code we write.

let [firstBook, secondBook] = library.titles;

Here, the variable firstBook corresponds to the 0th index in the library.titles array (‘The Inugami Clan') and the variable secondBook corresponds to the 1st index in the library.titles array (‘The Three Coffins').

The Result:

console.log(firstBook, secondBook);

image

But now, let's say we wanted to pick two titles but this time, take the first title (index 0) from the array and the third (index 2). In other words, we want to extract selected elements like we did earlier and skip a certain index position. You can give this a try by yourself and then come back to check the solution.

So, let's see how we can do that.

let [firstBook, , secondBook] = library.titles;

Just like earlier, the double comma in the middle of firstBook and secondBook means that the index corresponding to the empty element is skipped and therefore our second title (secondBook) will now be the 2nd index position in the library.titles array (‘In Search of Lost Time').

And then we check for the result:

console.log(firstBook, secondBook);

image

As you can see, this is really powerful. Destructuring can be used to do a lot of cool things.

So, now, let's say that we want to pick the title at the 1st index (‘The Three Coffins') as our first title and the title at the 0th index (‘The Inugami Clan') as our 2nd title (basically, we want to swap the status of the first and second titles).

As you can see from the library.titles array, right now, without swapping, the first title we are picking is ‘The Inugami Clan' whereas the second title we are picking is ‘The Three Coffins'. Now, we want to switch these.

Again, to do this without destructuring, we'd have to do this:

    let [firstBook, secondBook] = library.titles;

    console.log(‘First pick: ‘+firstBook+', Second pick: ‘+secondBook);

First, we're going with our original picks. We can check the initial status of the first and second picks by logging the result to the console:

image

And then we perform a traditional swapping.

    const tmp = firstBook;

    firstBook = secondBook;

    secondBook = tmp;

    console.log(‘First pick: ‘+firstBook+', Second pick: ‘+secondBook);

image

But with destructuring, again, this whole process can be made a lot easier.

This is how we do it:

    let [firstBook, secondBook] = library.titles;

    [firstBook, secondBook] = [secondBook, firstBook];

    console.log(‘First pick: ‘+firstBook+', Second pick: ‘+secondBook);

image

And there we go.

Extracting Elements from an Array Returned by a Function

And now, something new. Yet another nifty feature of destructuring is that we can have a function return an array and then we can immediately destructure the result in different variables. This allows us to return multiple values from a function. To try this out, let's add a function to the library object.

Here is what our updated library object looks like with the lend() function (to borrow 2 titles) added to it.

const library = {
  name: "Soumadri's Fiction Book Shelf",

  location: "1234 Fiction Palace, Calcutta, India",

  genres: [
    "Mystery",

    "Horror",

    "Fantasy",

    "Sci-Fi",

    "Literary Fiction",

    "Historical Fiction",
  ],

  titles: [
    "The Inugami Clan",

    "The Three Coffins",

    "In Search of Lost Time",

    "Sandman",

    "The Left Hand of Darkness",

    "The Complete Works of H.P. Lovecraft",

    "Do Androids Dream of Electric Sheep?",

    "In the Woods",

    "In a Glass Darkly",

    "Fingersmith",
  ],

  authors: [
    "Neil Gaiman",

    "Ursula Le Guin",

    "Sheridan Le Fanu",

    "H.P. Lovecraft",

    "Marcel Proust",

    "Tana French",

    "John Dickson Carr",

    "Seishi Yokomizo",

    "Philip K. Dick",

    "Sarah Waters",
  ],

  lend: function (firstBookIndex, secondBookIndex) {
    return [this.titles[firstBookIndex], this.titles[secondBookIndex]];
  },
};

We have added the function lend() to the library object. This is a function that accepts two parameters — an index position for the first title and another index position for the second title.

The user borrows two books by providing the index number for each of the titles. And we're returning the values (in the form of an array) from the corresponding positions in the library.titles array, that is based on the positions that were passed as parameters.

So now, let's borrow our books.

console.log(library.lend(2, 6));

Our result:

image

We picked index positions 2 and 6 from the library.titles array and those corresponding titles were what we got back as a result in the form of an array.

So now, let's destructure this array.

let [firstBook, secondBook] = library.lend(2, 6);

Let's log these values.

console.log(firstBook, secondBook);

image

And indeed, we get ‘In Search of Lost Time' and ‘Do Androids Dream of Electric Sheep?'.

So, this is how we can receive 2 or more return values from a function. This could have been done without destructuring as well but this is a very neat and handy way to immediately create two or more variables out of a function call.

Nested Destructuring

Let's take a look at what happens if you have a nested array (an array inside an array).

const nested = [1, 3, [2, 4]];

So now, based on what we have learned so far, let's try to get the values 1 (0th index) and the nested array [2, 4] (2nd index). We will be skipping the value at the 1st index position (3). I'd suggest giving this a try yourself before checking out the solution.

Okay, so I hope you were able to pull it off. In case you weren't, no worries. Here's how we are going to go about doing this.

const [i, , j] = nested;

console.log(i, j);

And yup, we have our desired result.

This is fantastic but what if we wanted all the individual values and not the whole nested array? If you think about it logically, it's actually pretty simple. Then, we'd simply have to do destructuring inside destructuring. So let's try to retrieve 3 values — 1, 2, 4 — separately. We'll skip over the 1st index again.

const [i, , [j, k]] = nested;

We are performing an array destructuring (denoted by [] on the left side of the = operator) inside an array destructuring. Thus, j and k will get the individual values of 2 and 4 respectively.

console.log(i, j, k);

And yes, there we have it.

Setting Default Values

And finally, we can also set default values for the variables when we are extracting them. This is going to be super helpful when we don't know the length of the array that we are retrieving values from (which is very common in real-world applications and projects).

Let's say we have an array (right-hand side) whose values we don't know (I'm going to set the values here of course, but just pretend that we are unaware of the length and the values for the sake of this lesson).

const [p, q, r] = [8, 9];

Now if we try to log the values:

console.log(p, q, r);

image

That's right. We get undefined as the value of r. The workaround to this problem is setting default values. We simply set the default values of p, q, and r to 1. In case there are the values available on the corresponding index position, the default value will get overwritten. In case there isn't a corresponding index position on the right-hand side, then the default value will remain. Let's try this out.

const [p = 1, q = 1, r = 1] = [8, 9];

console.log(p, q, r);

image

As you can see, p and q have the values 8 and 9 whereas r now has its default value, which was 1.

Conclusion

That's it, congratulations on reaching the end of this article. I'd like to thank Jonas Schmedtmann and his excellent and comprehensive Udemy course for giving me a clear and proper understanding of topics like these. I hope this little guide proves to be useful for you as well. If you have any queries or observations, feel free to make a comment.




Continue Learning