This content originally appeared on Go Make Things and was authored by Go Make Things
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"
console.log(entree);
// logs "chips"
console.log(side);
Here’s a demo for you to play with.
⏰ Last Chance! A new session of the Vanilla JS Academy starts on Monday. Join today and get 25% off registration.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2023-01-23T14:30:00+00:00) The ins-and-outs of array destructuring with vanilla JS. Retrieved from https://www.scien.cx/2023/01/23/the-ins-and-outs-of-array-destructuring-with-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.