Skip to main content Accessibility Feedback

The ins-and-outs of array destructuring with vanilla JS

Last week, we learned how to destructure objects, and how to combine destructuring with the spread operator.

Today, we’re going to learn how to destructure arrays. Let’s dig in!

Imagine you had an array of lunch items, and you wanted to pull them out into individual variables for the entree, drink, side, and desert.

You could use bracket notation to get those items.

let lunch = ['turkey sandwich', 'soda', 'chips', 'cookie'];

let entree = lunch[0];
let drink = lunch[1];
let side = lunch[2];
let desert = lunch[3];

Destructuring provides a simpler way to do to the same thing.

You define an array of variables, and the destructuring syntax will pull the values at the matching indexes out and assign them to the variables.

let [entree, drink, side, desert] = lunch;

// logs "turkey sandwich"

// logs "chips"

Here’s a demo for you to play with.