Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Array destructuring – JavaScript

Length: 10 minutes

Summary

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

Details

Array destructuring is a short way of splitting the values in an array into separate variables.

To destructure an array, first declare the variables you want to use.

let a, b;

Next, wrap the variables in square brackets on a new line, separated by commas.

let a, b;
[a, b]

Next, add an equals sign followed by the array and semicolon.

let a, b;
[a, b] = [1, 2];
// a = 1
// b = 2

It’s possible to declare the variables and destructure the array in one line, like this:

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

If you have more variables on the left side than values on the right, the left over variables will be undefined.

let [a, b, c] = [1, 2];
// a = 1
// b = 2
// c is undefined

If you have more values on the right side than variables on the left, the extra values will be ignored.

let [a, b] = [1, 2, 3];
// a = 1
// b = 2
// 3 will not be stored in a variable

Demo

Exercises

let [a, b] = [1, 2]
a
b

References

Destructuring assignment on MDN

Back to: JavaScript Reference > JS Data Types