Skip to content

Destructuring Arrays

JavaScript1 min read

Destructuring Arrays

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:

1const trees = ["spruce", "elm", "maple", "aspen", "walnut"];
2
3const [tree1, tree2, ...otherTrees] = trees;
4
5console.log(tree2);
6> 'elm'
7
8console.log(otherTrees);
9> [ '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!

1const trees = ["spruce", "elm", "maple", "aspen", "walnut"];
2
3const [tree1] = trees;
4
5console.log(tree1);
6> '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:

1const trees = ["spruce", "elm", "maple", "aspen", "walnut"];
2
3const [,,mapleTree] = trees;
4
5console.log(mapleTree);
6> '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:

1const trees = ["spruce", "elm", "maple", "aspen", "walnut"];
2
3[trees[0], trees[1]] = [trees[1], trees[0]];
4
5console.log(trees);
6> [ '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 🔥

© 2021 by Jonathan Speek