Search code examples
javascriptcomma-operator

Comma operator on defining variables


I'm interesting in logic which used to split string into expressions.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator says

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

The question is:

If I have string of code

 var x = 1, y = 2, z = 3;

where I can read why js recognize it as

var (x = 1), (y = 2), (z = 3);

and not as

var x = (1, y = 2, z = 3); // => x should be 3

Solution

  • You are looking in the wrong place - you should be looking at the var definition: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var

    basically, syntax of var is following:
    var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]]];