Question

Possible to assign to multiple variables from an array?

Is it a standard way to assign to multiple variables from an array in JavaScript? In Firefox and Opera, you can do:

var [key, value] = "key:value".split(":");
alert(key + "=" + value); // will alert "key = value";

But it doesn't work in IE8 or Google Chrome.

Does anyone know a nice way to do this in other browsers without a tmp variable?

var tmp = "key:value".split(":");
var key=tmp[0], value=tmp[1];

Is this something that will come in an upcoming JavaScript version, or just custom implementation in FF and Opera?

 45  37929  45
1 Jan 1970

Solution

 26

Destructuring assignment was standardized in ECMAScript 2015 (a.k.a. ES6). But not all browsers have implemented destructuring yet (as of March 2016), and even when they do it will take a while before users update to a browser with support. See examples in the spec for all the awesome things you can do. Here are some:

// Assign from array elements
var [key, value] = "key:value".split(":");
// key => 'key'
// value => 'value'

// Assign from object properties
var {name: a, age: b} = {name: 'Peter', age: 5};
// a => 'Peter'
// b => 5

// Swap
[a, b] = [b, a]
// a => 5
// b => 'Peter'

Because this feature breaks backwards compatibility, you'll need to transpile the code to make it work in all browsers. Many of the existing transpilers support destructuring. Babel is a very popular transpiler. See Kangax´s table of browser and transpiler ES6-support.

More info:

Compatibility table for ES6 browser support

Exploring ES6 - Destructuring chapter

2014-03-03

Solution

 9

If you want to know what's coming, read the section on Destructuring Assignment.

https://developer.mozilla.org/en/New_in_javascript_1.7

What language features you can use is always dependent on your environment.

Developing for Mobile Safari (or a web stack for other browsers like the Palm Pre, Android, etc.) or AIR, for example, is more predictable than developing for the web at large (where you still have to take even IE6 into account).


A cross-browser solution to the problem at hand would be to initialize an array that had a list of the variables you want to fill in window.variable format, then just loop through. Can't imagine why you'd do it though. Seems like there would always be a better solution.

2009-05-25