How to Unpack Array in JavaScript

In this post, we will see how to unpack array in JavaScript.

Ways to Unpack array in JavaScript

There are multiple ways to do it. Let’s go through them.

Using Destructuring Syntax

To Unpack array in Javascript into separate variable:

Let’s see with the help of example:

Output:

You can also do it by assigning array directly.

Output:

You can also use default value.

Output:

As you can see we provided default values for three variables india, france and china. Since array have two elements in array, india and france values got overriden and china had default value.

Using index based

If you are looking for cross browser solution, then you can assign variable on the basis of index.

Output:

Using spread operator

Spread operator was introduced in 2016.

Spread operator(...) allows iterable such array or string to expand where multiple arguments(for function calls) or elements(for array literals) are expected.

Here is simple example:

Output:

What happens if there are more elements in array?
If there are more elements in array, it will just assign x and y to first two elements of array.

Output:

What happens if there are more parameters in function?
If there are more parameters in array, it will just assign x and y to first two elements of array. Other parameters will take default value.

Output:

Let’s provide default value as 1 to parameter z.

Output:

Conclusion

To Unpack Array in JavaScript into separate variable, you can use Destructuring assignment, spread operator or index based assignment.

That’s all about how to unpack array in JavaScript.

Was this post helpful?

Leave a Reply

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