Table of Contents
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:
- Use destructuring assignment to unpack array in separate variable.
Let’s see with the help of example:
1 2 3 4 5 6 7 |
var countryArray = ['India','France'] var [india, france] = countryArray; console.log(india); console.log(france); |
Output:
1 2 3 4 |
India France |
You can also do it by assigning array directly.
1 2 3 4 5 |
var [india, france] = ['India','France']; console.log(india); console.log(france); |
Output:
1 2 3 4 |
India France |
You can also use default value.
1 2 3 4 5 6 |
const [india = 'c1', france = 'c2', china = 'c3'] =['India','France']; console.log(india); console.log(france); console.log(china); |
Output:
1 2 3 4 5 |
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.
1 2 3 4 5 6 7 8 |
var countryArray = ['India','France','China'] var india = countryArray[0]; var france = countryArray[1]; console.log(india); console.log(france); |
Output:
1 2 3 4 |
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:
1 2 3 4 5 6 |
let numArr = [10, 20]; let multiply = function(x, y) { return x * y; }; var result = multiply(...numArr); console.log(result); |
Output:
1 2 3 |
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.
1 2 3 4 5 6 |
let numArr = [10, 20,30]; let multiply = function(x, y) { return x * y; }; var result = multiply(...numArr); console.log(result); |
Output:
1 2 3 |
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.
1 2 3 4 5 6 |
let numArr = [10, 20]; let multiply = function(x, y, z) { return x * y * z; }; var result = multiply(...numArr); console.log(result); |
Output:
1 2 3 |
NaN |
Let’s provide default value as 1 to parameter z
.
1 2 3 4 5 6 |
let numArr = [10, 20]; let multiply = function(x, y, z=1) { return x * y * z; }; var result = multiply(...numArr); console.log(result); |
Output:
1 2 3 |
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.