Destructuring arrays

Destructuring arrays

How to destructure arrays in JavaScript

ยท

6 min read

Destructuring is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Destructuring assignment is a cool feature that came along with ES6. When we destructure an array, we are copying the values of its elements into variables. When destructuring an array, we use their positions (or index) in an assignment.

Basic Array Destructuring

When we want to take values from an array and use them as separate variables, we usually write code like this:

let myArray = ["Hello", "World"];
let first = myArray[0];
let second = myArray[1];

Since the major JavaScript ES2015 update, we can now do the same task like this:

let myArray = ["Hello", "World"];
let [first, second] = myArray;

console.log(first);             // Hello
console.log(second);      // World

The variables are assigned values corresponding to their order. Array destructuring syntax is like regular variable assignment syntax(let x = y). The difference is the left side consists of one or more variables in an array.

Assignment separate from declaration

A variable can be assigned a value via destructuring separate from the variable's declaration.

let firstName, lastName;
[firstName, lastName] = ["John", "Smith"];

console.log(firstName);      // John
console.log(lastName);      // Smith

If the number of variables passed to the destructuring array literals are more than the elements in an array, variables that are not mapped to any element in the array will return undefined.

let numbers = [1, 2];
let [a, b, c] = numbers;

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

Default values

A variable can be assigned a default in case the value unpacked from the array is undefined. It provides a fallback when nothing is found.

let a, b;
[a = 24, b = 96] = [];

console.log(a);     // 24
console.log(b);    // 96

let a, b;
[a = 24, b = 96] = [1, 2];

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

Skipping items in an array

We can skip or ignore items we do not want to assign to local variables and only assign the ones we are interested in. We use the comma separator to skip items when working with a large amount of data. If you want to choose random elements from a given array, then an array destructuring is done like this:

let [greeting,,, name] = ["Hello", "I", "am", "Tracy"];

console.log(greeting);     // Hello
console.log(name);         // Tracy

Interchanging or Swapping Variables

We can swap two variable values when destructuring arrays.

let a = 2;
let b = 4;

[a, b] = [b, a];
console.log(a);      // 4
console.log(b);     // 2

Assigning the rest of an array into a variable using the Rest parameter (...)

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest parameter. The Rest parameter appears on the left hand side when destructuring. The Rest variable must always be the last otherwise a syntax error is thrown.

let oceans = ["Indian", "Pacific", "Atlantic", "Arctic", "Southern"];
let [first,, third, ...others] = oceans;

console.log(first);      // Indian
console.log(third);     // Atlantic
console.log(others);   // ["Arctic", "Southern"]

Parsing returned array from functions

A function can return an array of values. Array destructuring makes it more precise to parse the returned array from functions.

function children() {
       return ["Eve", "Paul", "Beatrice", "Stella"];
}

let [a, b, c, d] = children();
console.log(a);        // Eve
console.log(b);       // Paul
console.log(c);      // Beatrice
console.log(d);     // Stella

Destructuring nested arrays.

You can also do nested destructuring with arrays. With an array of arrays, you can copy each element of each inner array into its own variable.

let numbers = [1, 2, 3, [5, 10, 15]];
let [one, two, three, [five, ten, fifteen]] = numbers;

console.log(one);    // 1
console.log(five);    // 5

Multiple Array Destructuring

You can also destructure an array more than once.

let countries = ["Uganda", "Kenya", "Tanzania", "Rwanda", "Burundi"];
let [a, b,, d] = [f, ...rest] = countries;

console.log(a);              // Uganda
console.log(b);             // Kenya
console.log(d);            // Rwanda
console.log(f);            // Uganda
console.log(rest);      // ["Kenya", "Tanzania", "Rwanda", "Burundi"]

Conclusion

With destructuring assignment, we can quickly extract values from arrays and put them into their own variables as seen in the examples above.

Thanks for reading!!