views:

101

answers:

1

Firefox 3.5.3 (at least) allows me to write code like :

var array = [4, 5, 6];
var foo, bar, baz;
[foo, bar, baz] = array;

at which point

foo => 4
bar => 5
baz => 6

which can be quite helpful for code clarity.

Is that considered ECMAScript-compliant? I didn't see anything in the specification, but JSLint returns an error.

+2  A: 

No, that's a feature introduced in JavaScript 1.7 called destructuring assignment. JavaScript is not ECMAScript. ECMAScript is the attempted standardization of some JavaScript features. There are only two JavaScript engines: (Spider|Trace|Action)Monkey and Rhino. Every other engine is an ECMAScript engine.

Here are some examples:

var {a, b} = {b:2, a:1}; // a === 1, b === 2
var [c, d] = [3, 4]; // c === 3, d === 4
var {x: e} = {x: 5}; //  e === 5
function f({a, b: c}, [d, e]) {
  // same as: var [{a, b: c}, [d, e]] = arguments
}

Opera partially implements some destructuring assignment. It doesn't support it for objects or in function arguments, but it does support your simple example.

Eli Grey
ah. I figured it was going to be a newer feature. And since 1.7 isn't fully supported yet, guess I have to stick with the more verbose option. Thanks!
Jason Persampieri
Late comment, but I was searching on the subject. Destructuring assignment was a feature planned for the now scrapped ECMAScript 4th Edition. It's kind of sad it didn't make it into ECMAScript 5.
Andy E
It looks like it's on the table for ecmascript:harmony http://wiki.ecmascript.org/doku.php?id=harmony:destructuring
Sean McMillan
I'm pretty sure he was referring to ECMAScript 3, so I answered accordingly. I agree that I should have mentioned it being in harmony, though I'm not even sure if it was, back when I posted this a year ago.
Eli Grey