Carson Myers Carson Myers - 1 year ago 138
Javascript Question

Unpacking array into separate variables in JavaScript

This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

In python I can do this:

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

how do I do that in JavaScript?

Answer Source

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

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

ES6 will allow destructuring assignment:

var [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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download