DEV Community

nonseodion
nonseodion

Posted on

6 Things You Need To Completely Understand Array Destructuring in Javascript (ES6)

It’s tedious accessing the elements of an array repeatedly, especially if that array has few elements.
Destructuring was introduced with ES6 in 2015 to make accessing array elements and object properties easier. My previous article covers destructuring objects in JavaScript.

Destructuring makes it possible to assign elements in an array to variable names using an assignment operator, =, and an array literal, [...]. With these, multiple assignments are done in a single expression. If you would want to see how array element assignments in JavaScript would have been done without destructuring I’d recommend using Babel. You can simply copy the code snippets on this article and paste them on Babel.

1. Basic Destructuring

Destructuring is done by placing an array literal containing variable names on the left side of an assignment operator and the array to be accessed on the right. The variable names are assigned the elements on the other array which have the same index with them. Array destructuring is done using the index of array elements.

accessing array elements pre-ES6

let brands = ["Nike", "Gucci", "Adidas"];
console.log(brands[0], brands[1], "and", brands[2], "are in vogue now.");
//Output: Nike Gucci and Adidas are in vogue now.

accessing array elements post-ES6

let brands = ["Nike", "Gucci", "Adidas"];
let [nike, gucci, adidas] = brands;
console.log(nike, gucci, and, adidas, are in vogue now.);
//Output: Nike Gucci and Adidas are in vogue now. 

From the code snippet above, nike, gucci and adidas are assigned the corresponding elements in the array that share the same index with them.

let nike, gucci, adidas;
let brands = ["Nike", "Gucci", "Adidas"];
[nike, gucci, adidas] = brands;
console.log(nike, gucci, and, adidas, are in vogue now.);

Declaration of variable names can also be done separately before the assignment. Unlike object destructuring, this does not require brackets around the destructuring expression.

2. Default Values

Unassigned identifiers are given the value, undefined. It is assigned by default to variable names that don’t have a corresponding array element sharing the same index with them.

let brands = ["Nike", "Gucci"];
let [nike, gucci, adidas] = brands;
console.log(adidas);
//Output: undefined

The variable name adidas is assigned undefined.

Unassigned values don’t give errors. Array elements that don’t get assigned to variable names are completely ignored and no error is thrown.

let brands = ["Nike", "Gucci", Adidas];
let [nike, gucci] = brands;
console.log(I love, nike, and, gucci);
//Output: I love Nike and Gucci

Explicit Default Values

Default values can be defined explicitly for the variable names by the programmer. These values serve as fallback when they don’t have a corresponding array element sharing the same index with them.

let brands = ["Nike", "Gucci"];
let [nike, gucci=vintage, adidas=Adidas] = brands;
console.log(I love, adidas, and, gucci);
//Output: I love Adidas and Gucci

The variable names, adidas and gucci are given default values. gucci is assigned a corresponding element in the array whose value overrides the default value, adidas isn’t assigned any element which causes the assignment to fall back to the default value.

3. Ignoring some values

Not all values are needed from an array always, values which are of no interest can be skipped. To skip a value, we skip its corresponding variable name but leave the comma.

let brands = ["Nike", "Gucci", "Adidas", Versace];
let [nike, , , versace] = brands;
console.log(I love, nike, and, versace);
//Output: I love Nike and Versace

The array elements, Nike and Gucci are skipped by skipping their variable names and leaving only the commas. But skipping array elements like this can be tedious and is prone to errors, like missing commas.

A better method of doing this requires knowledge of object destructuring, you can check my article on that. Arrays are objects in JavaScript, try running typeof [] in your browser console, it’ll produce object. The keys of an array are the index of its elements—the properties of the array.

To assign the variables, we consider the array as an object and change the keys (indices) to the variable names that we want.

let brands = ["Nike", "Gucci", "Adidas", Versace];
let {0:nike,  2:versace} = brands;
console.log(I love, nike, and, versace);
//Output: I love Nike and Versace

We change the indices of the first and last element to the variable names we want and access the corresponding array elements at that index.

4. Using the Spread syntax and Rest parameter

The spread and rest parameter make use of the three-dot notation, ....

Using Rest

When ... appears before a variable name yet to be assigned, it usually acts as a rest parameter. After assigning values to some variable names, the remaining elements might need to be tracked. The rest parameter is used to put the rest of the array elements in an array. It must always appear at the end of the array literal.

let brands = ["Nike", "Gucci", "Adidas", Versace];
let [nike, gucci, ...lower] = brands;
console.log(lower);
//Output: ["Adidas", "Versace"]

The rest parameter puts the rest of the elements in the variable name, lower.

Using Spread

When ... appears before an array, it’s usually inside another array or is part of an argument in a function and it’s used as spread syntax. It spreads the elements of the array into the other array if in an array, or the argument of the function if in a function call.

let lower = ["Adidas", "Versace"];
let [nike, gucci, adidas, versace] = ["Nike", "Gucci", ...lower];
console.log(nike, gucci, versace, and, adidas, are in vogue now.);
//Output: Nike Gucci Versace and Adidas are in vogue now.

The spread syntax spreads the elements of the array, lower, into the outer array which makes Adidas and Versace available as array elements.

5. Multiple Arrays

Did you know the below code snippet is valid?
a = b = 4;
The variables, a and b will end up with the value, 4. This makes it possible to destructure more than one array in a single expression.

let brands = ["Nike", "Gucci", "Adidas", Versace];
let [nike, gucci, adidas, versace] = [latest, vintage, ...lower] = brands;
console.log(nike, gucci, versace, and, adidas, are in vogue now.);
//Output: Nike Gucci Versace and Adidas are in vogue now.

console.log(latest, is better than, vintage);
//Output: Nike is better than Gucci

console.log(...lower);
//Output: ["Adidas", "Versace"];

6. Nested Arrays

To destructure a nested array you’ll need a nested array literal with variable names.

let brands = ["Nike", ["Gucci", "Adidas"], Versace];
let [nike, [ gucci, adidas], versace] = brands;
console.log(nike, gucci, versace, and, adidas, are in vogue now.);
//Output: Nike Gucci Versace and Adidas are in vogue now.

The nested and parent arrays are destructured with an array literal that has the same structure as them. All elements of both arrays don’t need to have corresponding variable names.

Some Uses of Array Destructuring

1. Destructuring returned function values

If a function execution returns an array, it can be destructured to access its elements.

function brands(){
return ["Nike", "Gucci", "Adidas", "Versace"];
}
let [nike, gucci, adidas, versace] = brands();
console.log(nike, gucci, versace, "and", adidas, "are in vogue now.");
//Output: Nike Gucci Versace and Adidas are in vogue now.

The array returned from the function, brands is destructured.

2. Destructuring function arguments

Placing an array literal as a function parameter helps to destructure array arguments passed to the function during a function call.

function brands([nike, gucci, adidas, versace]) {
console.log(nike, gucci, versace, "and", adidas, "are in vogue now.");
}

brands(["Nike", "Gucci", "Adidas", "Versace"]);
//Output: Nike Gucci Versace and Adidas are in vogue now.

The array elements are destructured during the call of brands.

3. Swapping Variables

Variables can now easily be swapped in a single expression unlike the previous method of finding a temporary variable to hold an intermediate value which usually took three lines.

let gucci = Gucci;
let versace = Versace;

//We shall swap the values of versace and gucci variables

//Pre-ES6 
let temp = gucci;
gucci = versace;
versace = gucci;
console.log(versace, is better than, gucci);
//Output: Gucci is better than Versace.

//Post-ES6
[gucci, versace] = [versace, gucci];
console.log(versace, is better than, gucci);
//Output: Gucci is better than Versace.

From the code snippet swapping variables has become easier and faster with ES6.

Wrapping Up

Using destructuring in your code for assignments helps to reduce time spent in writing code and you write shorter lines of code. This will reduce errors and make you write cleaner code. Although not all browser versions support it yet, most do. You can find out more about browsers that support it on CanIUse.Com.

Top comments (0)