DEV Community

loading...
Cover image for Destructuring Arrays in JS

Destructuring Arrays in JS

jonathanspeek profile image Jonathan Speek ・2 min read

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;

console.log(tree2);
> 'elm'

console.log(otherTrees);
> [ 'maple', 'aspen', 'walnut' ]
Enter fullscreen mode Exit fullscreen mode

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;

console.log(tree1);
> 'spruce'
Enter fullscreen mode Exit fullscreen mode

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;

console.log(mapleTree);
> 'maple'
Enter fullscreen mode Exit fullscreen mode

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]];

console.log(trees);
> [ 'elm', 'spruce', 'maple', 'aspen', 'walnut' ]
Enter fullscreen mode Exit fullscreen mode

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!

To dive deeper into arrays, check out my course Working with Arrays 🔥

Discussion (0)

pic
Editor guide