Carson Myers Carson Myers - 8 months ago 61
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?


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;