Skip to main content

Command Palette

Search for a command to run...

Array destructuring in JavaScript

Updated
2 min read
Array destructuring in JavaScript

When we have an array and we want to extract the variables we can do it like this:

const fruits = ['apple', 'strawberry', 'banana', 'orange'];

const apple = fruits[0] // apple

const strawberry = fruits[1] // strawberry

const banana = fruits[2] // banana

const orange = fruits[3] // orange

But we can make it easier:

const fruits = ['apple', 'strawberry', 'banana', 'orange'];

const [ apple, strawberry, banana, orange ] = fruits

Now there is a variable called apple that has the 'apple' value assigned.

How does it work?

This is called destructuring. We assign the first new variable to the first element of the array. And the same for the other variables and values.

Let's see it again but with different names, and we won't create the same number of variables as values of the array:

const fruits = ['apple', 'strawberry', 'banana', 'orange'];

const [ firstFruit, secondFruit ] = fruits

Now we have two new variables: firstFruit and secondFruit. firstFruit has the value of the first element of the fruits array, and secondFruit has the second element of the fruits array.

I like to think it like this: "I will create a variable called x from the array y"

const [newVariable1, newVariable2] = originalArray

But we won't always know the length of the array, so we can extract for example the first two positions of the array and then group the other on another array.

We'll use the rest operator (...)

const fruits = ['apple', 'strawberry', 'banana', 'orange'];

const [ firstElement, secondElement, ...otherElements ] = fruits

Can you think the value of each one of this new variables?

firstElement -> 'apple'

secondElement -> 'strawberry'

otherElements -> [ 'banana', 'orange' ]

We have grouped the rest of the elements of the array to a new one array with the name we gave to the variable, in this example to otherElements.

The magic happens with the three dots before the name of the future new variable.

That's how you can destructure an array and go further with the rest operator!