Unfamiliar variable assignment with parentheses and commas

Why assigning values ​​with parentheses like this only evaluates the last value

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

      

It seems that a parenthesis is also required

var a = 1, 5 - 1; //SyntaxError: Unexpected number

      

+3


source to share


1 answer


The symbol ,

has several similar but distinctly different roles in JavaScript syntax. In a declaration, a var

comma separates the variable declaration clauses. However, in an expression, the comma operator provides a way to collect multiple expressions together in a form that is syntactically equivalent to a single expression. This is somewhat useful in some rare cases.

Thus, the parentheses matter here because without them, the parser expects each comma-separated clause to be a variable declaration and (optional) initialization. Within parentheses, the right-hand side of the initialization is syntactically a single expression, even if they are three separate unrelated expressions linked by the comma operator.

The comma operator in expressions is perhaps useful when a situation arises that involves syntax that allows one expression, but you really want to use more than one. The best example is the third section in the header of the loop for

. If you need to increment two separate variables, then it (may) be clearer for that in the header of the loop; however, there is only one expression. Thus, the comma operator allows you to cheat:



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

      

Note that the comma in the first sentence of the header is for

not a comma operator; it is a comma that separates the variable declaration clauses. (I think some people may use the term "comma operator" for this, but what I mean is that it does not separate the list of expressions.)

+10


source







All Articles