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'

Leave a Comment