Skip to content

Destructuring arrays in JS

Snow and forest trees

A somewhat new tool in JavaScript is destructuring. Sounds scary, but after working with it a little it becomes less intimidating, I swear. Destructuring allows us to just take a few elements (also works with objects and you'll see it plenty in import statements) from our array and we can even rename them. Let's have a gander.

Let's make an array of trees and destructure to grab the first and second trees, separating them from the rest of the trees:

const trees = ["spruce", "elm", "maple", "aspen", "walnut"];

const [tree1, tree2, ...otherTrees] = trees;

> 'elm'

> [ 'maple', 'aspen', 'walnut' ]

What we're doing here is creating a new variable that holds the element at index 0, setting it equal to tree1, doing the same with index 1 of our trees array, then spreading the rest of the trees into a new variable called otherTrees.

This also works for any number of elements you want to grab. Maybe you only want to create a new variable from the first element in the array. We can do that!

const trees = ["spruce", "elm", "maple", "aspen", "walnut"];

const [tree1] = trees;

> 'spruce'

We can also skip elements in the array. For instance, to grab the maple tree, we can just provide a comma for each element we want to skip:

const trees = ["spruce", "elm", "maple", "aspen", "walnut"];

const [,,mapleTree] = trees;

> 'maple'

One really cool use for destructuring is when you need to swap 2 elements in an array. Say we wanted to switch the spruce and elm trees positions in the array of trees:

const trees = ["spruce", "elm", "maple", "aspen", "walnut"];

[trees[0], trees[1]] = [trees[1], trees[0]];

> [ 'elm', 'spruce', 'maple', 'aspen', 'walnut' ]

Destructuring can be a little tricky, but the more you see and use it, the easier it'll be to use in your own code. Be sure to take some time to explore uses in any codebase you're working in, you might be surprised just how much it's used!

Wanna get better at working with arrays in JS? Check out my latest course 🔥