Categories
JavaScript Answers

How to Unpack an Array into Separate Variables in JavaScript?

Spread the love

Oftentimes, we want to unpack JavaScript array entries into their own variables.

In this article, we’ll take a look at how to unpack a JavaScript array into separate variables with JavaScript.

Use the Destructuring Syntax

We should use the JavaScript array destructuring syntax to unpack JavaScript array entries into their own variables.

For instance, we can write:

const [x, y] = ['foo', 'bar'];
console.log(x);
console.log(y);

Then we assign 'foo' to x and 'bar' to y .

So x is 'foo' and y is 'bar' .

We can assign an array directly to variables on the left side.

For instance, we can write:

const arr = ['one', 'two'];
const [one, two] = arr;

We assign 'one' to one and 'two' to two .

Also, we can set a default value in case a value isn’t assigned to the variable.

To do this, we write something like:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one);
console.log(two);
console.log(three);

We assign default values to one , two and three with the assignment statements on the left side.

So one is 1, two is 2, and three is 'three' .

three is 'three' since there’s no array entry assigned to it.

Conclusion

We can unpack JavaScript array entries into their own variables easily by using the destructuring syntax.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *