32

For a project, a developer sent us a JS file with code similar to this:

var myList = [ 1, 2, 3 ];
var a, b, c;

[ a, b, c ] = myList;

It works in Opera 10.30, and Firefox 3.6.x, but it’s not okay for Opera 10.60, and Chrome.

It’s just curiosity: do you have any reference or link that says this code is compliant to the ECMAScript standard or not?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
napolux
  • 15,574
  • 9
  • 51
  • 70
  • I'm pleased to find that the feature has been introduced to desktop Chrome since Chrome version 49 (https://www.chromestatus.com/feature/4588790303686656 ). I've verified it in my Chrome extension code https://github.com/chuan6/webXi/commit/8283ea713ea5c8c050750b5cd64c6f922817f727#diff-b227432cc34ef4d8e3d6af1fcd6b24f5R86 . – leo Jul 12 '16 at 00:40
  • 2
    In case somebody comes here wondering, you can do `var [a,b,c] = myList;` with the same effect. – arekolek May 18 '17 at 00:26

4 Answers4

24

This is a feature called destructuring assignment, which was added in JavaScript 1.7 and ECMAScript 6. It is not a part of ECMAScript 5: What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
ide
  • 19,942
  • 5
  • 64
  • 106
12

Here’s an update on the subject: as of JavaScript version 1.7, destructuring assignments are supported by all major browsers: see browser compatibility.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

MDN’s documentation

So you can do:

let a, b;
[a, b] = ["Hello", "World"];

console.log(a); // "Hello"
console.log(b); // "World"

Or simply in one line if you're defining the variables:

let [a, b] = ["Hello", "World"];

console.log(a); // "Hello"
console.log(b); // "World"
Community
  • 1
  • 1
Ivan
  • 34,531
  • 8
  • 55
  • 100
5

This is destructuring assignment, available in Javascript 1.7 (mozilla) and some newer browsers: http://www.robertnyman.com/javascript/javascript-1.7.html#destructuring-assignment

Marko Dumic
  • 9,848
  • 4
  • 29
  • 33
2

Opera's older "futhark" JavaScript engine had support for this, but it was dropped in the new engine "carakan", because it was non-standard, not required on the web, and would complicate the new and very fast implementation.

hallvors
  • 6,069
  • 1
  • 25
  • 43