Unpacking array into separate variables in JavaScript

This is currently the only cross-browser-compatible solution AFAIK:

var one = arr[0],
    two = arr[1];

ES6 will allow destructuring assignment:

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

Or, to stick to your initial example:

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

You could also create a default value:

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

The question is rather old but I like to post this alternative (2016) solution: One can also use the spread operator "...".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

let xAndY = [42, 1337];
let f = function(x, y) { return x + y; };
f(...xAndY);

That's destructuring assignment. You can do it in some browsers with the following syntax:

[one, two] = arr;

It's supported in some of the latest browsers and transpilers like Babel and Traceur. This was a feature introduced with ECMAScript 4 which later became ECMAScript Harmony, which eventually became ES 2015.


You can use array's apply function if you want an array items to be passed as a function arguments.


Implementation of serious's idea.

http://jsfiddle.net/RichAyotte/6D2wP/

(function(a, b, c, d) {
    console.log(a, b, c, d);   
}.apply(this, ['a', 'b', 'c', 'd']));