Array destructuring

Earlier in this chapter, we discovered object destructuring. Array destructuring is another useful ES2015 feature (also supported by TypeScript). It works in a similar way to object destructuring, but with arrays instead.

We have all written code like this at some point:

const values = ['A', 'B', 'C']; 
 
const first = values[0]; 
const second = values[1]; 
const third = values[2]; 

It works fine, but it is also verbose. With array destructuring, we can easily extract elements of an array into other variables/constants.

Here's another version of the previous example, this time using array destructuring:

const values = ['A', 'B', 'C']; 
const [first,second,third] = values; 

The variables that we are destructuring the array elements into can be defined sooner as well.

It is also possible to define default values, in case some of the values we extract from the array are undefined:

const [first = 0, second = 1, third = 3] = ['A', undefined, 'B', 'C']; 
console.log(second); // 1 

Another cool trick that we can do with array destructuring is to swap elements in an array without relying on a temporary variable:

let x = 13; 
let y = 37; 
[x, y] = [y, x];

console.log(`${x} - ${y}`); // 37 - 13 

Isn't this cool? Here's one more:

const [x, , y] = [1, 2, 3]; // x === 1, y === 3

With the preceding example, you can skip any array elements when destructuring.

Here's one last tip before we move on—it is possible to extract a subset of the values into variables, then extract all of the remaining ones in another one:

const values = ['A', 'B', 'C', 'D']; 
const [first, ...allTheRest] = values; 
 
console.log(allTheRest); // 'B', 'C', 'D' 

Isn't that nice? Think about these tricks the next time you need to take elements out of an array!