Array Destructuring

Array destructuring syntax is very similar to object destructuring; it just uses array literal syntax instead of object literal syntax. The destructuring operates on positions within an array, rather than the named properties that are available in objects. For example:

  1. let colors = [ "red", "green", "blue" ];
  2. let [ firstColor, secondColor ] = colors;
  3. console.log(firstColor); // "red"
  4. console.log(secondColor); // "green"

Here, array destructuring pulls out the values "red" and "green" from the colors array and stores them in the firstColor and secondColor variables. Those values are chosen because of their position in the array; the actual variable names could be anything. Any items not explicitly mentioned in the destructuring pattern are ignored. Keep in mind that the array itself isn’t changed in any way.

You can also omit items in the destructuring pattern and only provide variable names for the items you’re interested in. If, for example, you just want the third value of an array, you don’t need to supply variable names for the first and second items. Here’s how that works:

  1. let colors = [ "red", "green", "blue" ];
  2. let [ , , thirdColor ] = colors;
  3. console.log(thirdColor); // "blue"

This code uses a destructuring assignment to retrieve the third item in colors. The commas preceding thirdColor in the pattern are placeholders for the array items that come before it. By using this approach, you can easily pick out values from any number of slots in the middle of an array without needing to provide variable names for them.

W> Similar to object destructuring, you must always provide an initializer when using array destructuring with var, let, or const.

Destructuring Assignment

You can use array destructuring in the context of an assignment, but unlike object destructuring, there is no need to wrap the expression in parentheses. For example:

  1. let colors = [ "red", "green", "blue" ],
  2. firstColor = "black",
  3. secondColor = "purple";
  4. [ firstColor, secondColor ] = colors;
  5. console.log(firstColor); // "red"
  6. console.log(secondColor); // "green"

The destructured assignment in this code works in a similar manner to the last array destructuring example. The only difference is that firstColor and secondColor have already been defined. Most of the time, that’s probably all you’ll need to know about array destructuring assignment, but there’s a little bit more to it that you will probably find useful.

Array destructuring assignment has a very unique use case that makes it easier to swap the values of two variables. Value swapping is a common operation in sorting algorithms, and the ECMAScript 5 way of swapping variables involves a third, temporary variable, as in this example:

  1. // Swapping variables in ECMAScript 5
  2. let a = 1,
  3. b = 2,
  4. tmp;
  5. tmp = a;
  6. a = b;
  7. b = tmp;
  8. console.log(a); // 2
  9. console.log(b); // 1

The intermediate variable tmp is necessary in order to swap the values of a and b. Using array destructuring assignment, however, there’s no need for that extra variable. Here’s how you can swap variables in ECMAScript 6:

  1. // Swapping variables in ECMAScript 6
  2. let a = 1,
  3. b = 2;
  4. [ a, b ] = [ b, a ];
  5. console.log(a); // 2
  6. console.log(b); // 1

The array destructuring assignment in this example looks like a mirror image. The left side of the assignment (before the equals sign) is a destructuring pattern just like those in the other array destructuring examples. The right side is an array literal that is temporarily created for the swap. The destructuring happens on the temporary array, which has the values of b and a copied into its first and second positions. The effect is that the variables have swapped values.

W> Like object destructuring assignment, an error is thrown when the right side of an array destructured assignment expression evaluates to null or undefined.

Default Values

Array destructuring assignment allows you to specify a default value for any position in the array, too. The default value is used when the property at the given position either doesn’t exist or has the value undefined. For example:

  1. let colors = [ "red" ];
  2. let [ firstColor, secondColor = "green" ] = colors;
  3. console.log(firstColor); // "red"
  4. console.log(secondColor); // "green"

In this code, the colors array has only one item, so there is nothing for secondColor to match. Since there is a default value, secondColor is set to "green" instead of undefined.

Nested Destructuring

You can destructure nested arrays in a manner similar to destructuring nested objects. By inserting another array pattern into the overall pattern, the destructuring will descend into a nested array, like this:

  1. let colors = [ "red", [ "green", "lightgreen" ], "blue" ];
  2. // later
  3. let [ firstColor, [ secondColor ] ] = colors;
  4. console.log(firstColor); // "red"
  5. console.log(secondColor); // "green"

Here, the secondColor variable refers to the "green" value inside the colors array. That item is contained within a second array, so the extra square brackets around secondColor in the destructuring pattern are necessary. As with objects, you can nest arrays arbitrarily deep.

Rest Items

Chapter 3 introduced rest parameters for functions, and array destructuring has a similar concept called rest items. Rest items use the ... syntax to assign the remaining items in an array to a particular variable. Here’s an example:

  1. let colors = [ "red", "green", "blue" ];
  2. let [ firstColor, ...restColors ] = colors;
  3. console.log(firstColor); // "red"
  4. console.log(restColors.length); // 2
  5. console.log(restColors[0]); // "green"
  6. console.log(restColors[1]); // "blue"

The first item in colors is assigned to firstColor, and the rest are assigned into a new restColors array. The restColors array, therefore, has two items: "green" and "blue". Rest items are useful for extracting certain items from an array and keeping the rest available, but there’s another helpful use.

A glaring omission from JavaScript arrays is the ability to easily create a clone. In ECMAScript 5, developers frequently used the concat() method as an easy way to clone an array. For example:

  1. // cloning an array in ECMAScript 5
  2. var colors = [ "red", "green", "blue" ];
  3. var clonedColors = colors.concat();
  4. console.log(clonedColors); //"[red,green,blue]"

While the concat() method is intended to concatenate two arrays together, calling it without an argument returns a clone of the array. In ECMAScript 6, you can use rest items to achieve the same thing through syntax intended to function that way. It works like this:

  1. // cloning an array in ECMAScript 6
  2. let colors = [ "red", "green", "blue" ];
  3. let [ ...clonedColors ] = colors;
  4. console.log(clonedColors); //"[red,green,blue]"

In this example, rest items are used to copy values from the colors array into the clonedColors array. While it’s a matter of perception as to whether this technique makes the developer’s intent clearer than using the concat() method, this is a useful ability to be aware of.

W> Rest items must be the last entry in the destructured array and cannot be followed by a comma. Including a comma after rest items is a syntax error.