In a previous article, we've shown how to use the JavaScript spread syntax, introduced in ES6. We're now continuing by showing how to destructure arrays and objects.

What is destructuring?

Destructuring is the process of unpacking data from arrays or objects, into distinct variables.

Destructuring from arrays

Given an array, we can "extract" some of its values:

let colours = ['red', 'blue', 'green'];
let [colour1, colour2] = colours;
console.log(colour1); // 'red'
console.log(colour2); // 'blue'

If not enough values are present, the destination is `undefined`:

let colours = ['red', 'blue', 'green'];
let [colour1, colour2, colour3, colour4] = colours;
console.log(colour4); // undefined

However, default values can be provides:

let colours = ['red', 'blue', 'green'];
let [colour1, colour2, colour3, colour4 = 'yellow'] = colours;
console.log(colour4); // 'yellow'

It is also possible to ignore certain values when required - notice the extra comma between `colour1` and `colour2` in the example below:

let colours = ['red', 'blue', 'green'];
let [colour1, , colour2] = colours;
console.log(colour2); // 'green'

Destructuring assignment

This is a slight various of the previous scenario.
Sometime we need to assign values to multiple variable at the same time and destructuring makes is simpler and visually more appealing:

let colour, score;
[colour, score] = ['blue', 42];

Destructuring from objects

This will feel very similar to the destructuring from arrays - however, the names of the variables to destructure to must match the name of the object properties:

let colour = { name: 'blue', score: 42};
let {name, score} = colour;
console.log(name);  // 'blue'
console.log(score); // 42

To unpack to different variable names, we need to specify both them alongside the object properties:

let colour = { name: 'blue', score: 42};
let {name: colourName, score: colourScore} = colour;
console.log(colourName);  // 'blue'
console.log(colourScore); // 42

And, just like before, we can speficy default values:

let colour = { name: 'blue', score: 42};
let {id: colourId = 1, name: colourName, score: colourScore} = colour;
console.log(colourId);  // 1

Next Steps