Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?

Tags:

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, Firefox 3.6.x but it's not ok for Opera 10.60 and Chrome.

It's just curiosity, do you have any reference or link that says this code is compliant to JS/ECMA standard or not?

What do you think?

like image 421
napolux Avatar asked Oct 21 '10 10:10

napolux


People also ask

Does JavaScript have multiple assignment?

“JavaScript allows multiple left-hand assignments” Well, if you're not familiar, in JavaScript you can write the variable assignment expressions like this. var a = b = c = d = 10; The assignment expressions are always evaluated from right-to-left.

What is an assignment operator in JavaScript?

Assignment operators. An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

What does the => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is the JavaScript expression of a/b c?

a = b can be seen as both a statement and an expression. The result of the expression is b . If the result of the expression a = b is b , then the expression a = (b = c) should be equivalent to b = c; a = c; (but this does not mean that a = b = foo() will call foo twice!).


2 Answers

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

like image 131
ide Avatar answered Sep 22 '22 00:09

ide


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" 
like image 41
Ivan Avatar answered Sep 23 '22 00:09

Ivan