Search code examples
javascriptexpressionvar

In Javascript: why does var a, b = 3 return undefined while b = 3 does not?


In the MDN the comma operator is described:

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

But why does

var a, b = 3

return undefined, while the expression

b = 3

will return 3, doesn't it?


Solution

  • This:

    var a, b = 3;
    

    is a VariableStatement. VariableStatement evaluation in "normal completion" to empty:

    1. Let next be the result of evaluating VariableDeclarationList.
    2. ReturnIfAbrupt(next).
    3. Return NormalCompletion(empty).

    This:

    b = 3;
    

    is an ExpressionStatement. ExpressionStatement evaluates to the result of the evaluating expression:

    1. Let exprRef be the result of evaluating Expression.
    2. Return ? GetValue(exprRef).