Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top