Array destructuring in Javascript

Array destructuring in Javascript

In this article, you are going to learn all about array destructuring in Javascript and some cool tricks you can perform using it, like swapping values of variables, returning multiple values from a function, copying an array, etc.

Essentially, we use destructuring in Javascript to unpack data from more complex data structures like arrays and objects into individual variables of choice, without having to repeat ourselves too much.

Check my video on this topic:

Otherwise, keep reading to know more and learn all about destructuring arrays.

Basics

When we declare and initialize a variable, essentially we pack the data into it. For example, let's suppose we create an array:

const numbers = [10, 20, 30, 40];

We can say we have packed the numbers 10, ..., 40 into the numbers variable.

Now, instead of doing the following to store individual elements of this array into variables and repeating ourselves too much:

const a = numbers[0];
const b = numbers[1];
/// ...

We can use destructuring to unpack this data:

const [a, b, c, d] = numbers;
console.log(a); // 10
console.log(d); // 40

Keep in mind that it's not needed to declare the variables in the same line as destructuring:

const a, b, c, d, e;

[a, b, c, d, e] = numbers;
console.log(a); // 10
console.log(e); // 50

If the number of values we are destructuring is less than the total number of elements in the array, we are going to destructure only the same number of elements from the beginning of the array:

const [a, c] = numbers;
console.log(a); // 10
console.log(c); // 20

But what if we try to destructure more values than there exist in the array? In that case the extra variables that map to non-existing array elements will have the value of undefined:

const [a, b, c, d, e, f] = numbers;
console.log(e); // undefined
console.log(f); // undefined

Default values for undefined elements

In the previous example we were trying to destructure variables that didn't exist in the array numbers. We can choose what would be the default values assigned to those variables in that case by using the = operator:

const [a, b, c, d, e = 0, f = 0] = numbers;
console.log(e); // 0
console.log(f); // 0

Ignoring elements

We can ignore some elements in sequence, if we don't want to destructure them:

const [a, , c, d, e, f] = numbers;
console.log(a); // 10
console.log(c); // 30

That being said, we can also ignore multiple values in a row like [a,,,d,e,f] = numbers, but the code gets quite unreadable that way, so try to avoid using it. As a matter of fact, there is already an ESLint rule out there that prevents ignoring more consecutive values (for more check eslint-plugin-unicorn)

Iterables

Since destructuring is just syntax sugar for iteration, it can be performed on any iterable, not just arrays. So, for example, a string is an iterable, so we can do this:

const [a, b, c, d] = "cool";
console.log(a, b, c, d); // c o o l

Nested array destructuring

We can also destructure nested arrays, i.e. arrays within arrays

const destination = ['Paris', [48.8566, 2.3522]];

const [city, [latitude, longitude]] = destination;
console.log(latitude, longitude); // 48.8566 2.3522

Tricks using array destructuring

OK, so now that we got the basics down, let's check out some tricks we can perform using destructuring in Javascript.

Swapping variables

Let's say we have variables a and b, and we want to swap their values so that a contains the value of b, and b contains the value of a. We can use array destructuring syntax to do that:

const a = 1;
const b = 2;
[b, a] = [a, b];

console.log(a); // 2
console.log(b); // 1

Multiple function return values

If we ever want to return more than one value from a function and capture those values where the function is called, again we can use array destructuring to achieve this:

function getPerson() {
    const name = "Johnny Knoxville";
    const age = 30;
    const phone = "123456"

    return [name, age, phone];
}

// ... somewhere else we call getPerson()
const [personName, personAge, personPhone] = getPerson();

console.log(personName); // "Johnny Knoxville"
console.log(personAge); // 30
console.log(personPhone); // 123456

Capturing the rest of an array as another array

When destructuring the first few values of an array, we may want to store the values that we haven't destructured into a new array.

To achieve this, we can use the spread operator ... to capture the rest of the elements into the new array:

const numbers = [1, 2, 3, 4, 5, 6, 7];
const [a, b, ...rest] = numbers;
console.log(rest); // [3, 4, 5, 6, 7];

An important point to note here is that the ...rest has to always be at the end of the array we use for destructuring, otherwise an error will be thrown. Another important thing about this to remember is that after this runs, the rest variable will hold an array that is a completely different array in memory than the numbers array, i.e. the remaining values from the numbers array are copied into a new array stored in the rest variable.

Because of this, we can utilize this as a trick to clone an array:

const numbers = [1, 2, 3, 4, 5, 6, 7];
const [...numbersCopy] = numbers;
console.log(numbersCopy); // [1, 2, 3, 4, 5, 6, 7]

numbersCopy[0] = 999;

// The original array stays the same
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]

Conclusion

That’s it when it comes to destructuring arrays in Javascript. Hope you can utilize the info presented here and take one more step towards writing DRY code.

We can use a similar syntax to destructure Javascript objects as well but to keep this article focused, I’m leaving that as a follow-up article - Object destructuring in Javascript.