javascriptsyntax

Does assignment with a comma work in JavaScript?


Why does aaa = 1,2,3 work and set the value of aaa to 1?

aaa = 1,2,3;
console.log(aaa);

Why doesn't var bbb = 1,2,3 work?

var bbb = 1,2,3;
console.log(bbb);

Why does var bbb = (1,2,3) work and set the value of bbb to 3?

var bbb = (1,2,3);
console.log(bbb);


Solution

  • There's a lot going on here, but basically, it comes down to the comma operator.

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


    This code:

    aaa = 1,2,3
    

    Is equivalent to:

    aaa = 1;
    2;
    3;
    

    So aaa is implicitly declared and assigned a value of 1. Notice that the output on the console is the result of the last statement, 3.


    This code:

    var bbb = 1,2,3
    

    Is a syntax error because commas in variable declarations are used to declare multiple variables in a single line. As the MDN article points out,

    Note that the comma in the var statement is not the comma operator, because it doesn't exist within an expression. Rather, it is a special character in var statements to combine multiple of them into one.

    So this code is roughly equivalent to:

    var bbb = 1;
    var 2;
    var 3;
    

    Of course, 2 is not a valid identifier, so it fails at that point.


    This code:

    var bbb = (1,2,3)
    

    Is very similar to the first, except because the numeric values are wrapped in a parentheses, they are evaluated first. So this is rougly equivalent to:

    1;
    2;
    var bbb = 3;