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:

var countryArray = ['India','France']

var [india, france] = countryArray;
console.log(india); 
console.log(france); 

Output:

India
France

You can also do it by assigning array directly.

var [india, france] =  ['India','France'];
console.log(india); 
console.log(france); 

Output:

India
France

You can also use default value.

const [india = 'c1', france = 'c2', china = 'c3'] =['India','France'];
console.log(india); 
console.log(france); 
console.log(china);

Output:

India
France
c3

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.

var countryArray = ['India','France','China']

var india = countryArray[0];
var france = countryArray[1];
console.log(india); 
console.log(france); 

Output:

India
France

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:

let numArr = [10, 20];
let multiply = function(x, y) { return x * y; };
var result = multiply(...numArr);
console.log(result);

Output:

200

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.

let numArr = [10, 20,30];
let multiply = function(x, y) { return x * y; };
var result = multiply(...numArr);
console.log(result);

Output:

200

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.

let numArr = [10, 20];
let multiply = function(x, y, z) { return x * y * z; };
var result = multiply(...numArr);
console.log(result);

Output:

NaN

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

let numArr = [10, 20];
let multiply = function(x, y, z=1) { return x * y * z; };
var result = multiply(...numArr);
console.log(result);

Output:

200

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.