Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unfamiliar variable assignment with parenthesis and commas

Tags:

javascript

Why does assigning values with parenthesis like this only evaluate to the last value

 var a = (1, 2, 5 - 1); //4

It also seems to require the parenthesis

var a = 1, 5 - 1; //SyntaxError: Unexpected number
like image 466
1252748 Avatar asked Nov 30 '14 19:11

1252748


2 Answers

The , symbol has several similar but distinctly different roles in JavaScript syntax. In a var declaration, the comma separates variable declaration clauses. In an expression, however, the comma "operator" provides a way to stuff several expressions together in a form that is syntactically equivalent to a single expression. That's somewhat useful in certain rare cases.

Thus, the parentheses make a difference here because without them, the parser expects each comma-separated clause to be a variable declaration and (optional) initialization. With the parentheses, the right-hand side of the initialization is a single expression, syntactically, even though it's three separate unrelated expressions connected by the comma operator.

The comma operator in expressions is arguably useful when there's a situation that involves syntax that allows for a single expression, but you really want to use more than one. The best example is the third clause in a for loop header. If you need to increment two separate variables, then it (may) be clearer to do that in the loop header; however, there's only provision for one expression. Thus the comma operator lets you cheat:

for (var a = 0, b = 1; a < limit; a++, b = something(b)) {
  // ...
}

Note that the comma in the first clause of the for header is not the comma operator; it's the comma that separates variable declaration clauses. (I guess some people might still use the term "comma operator" for that, but my point is that it's not separating a list of expressions.)

like image 50
Pointy Avatar answered Oct 29 '22 15:10

Pointy


The comma operator ',' evaluates each of its operands ( from left to right) and returns the value of the last operand.You can have multiple expressions evaluated with the final value been the value of the rightmost expression.

let x = 9;
x = (x++, x*2, x*3)

// output: x = 30

This use of compound expressions and assignment is helpful in conditional operators, in for loops.

Note: Without the parentheses,

let x = 9;
x = x++, x*2, x*3

// output: x = 27

From the documentation

var a, b, c;
a = b = 3, c = 4; // Returns 4 in console

console.log(a); // 3 (left-most)

var x, y, z;
x = (y = 5, z = 6); // Returns 6 in console

console.log(x); // 6 (right-most)

See also MDN operator precedence docs

like image 27
ax0r Avatar answered Oct 29 '22 13:10

ax0r