0

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?

try-catch-finally
  • 6,720
  • 6
  • 37
  • 64
  • 5
    That's not a comma operator, and `var b = 3` is not an expression. – JJJ Nov 22 '16 at 13:19
  • Try it in console: `ReferenceError: a is not defined` – Emil S. Jørgensen Nov 22 '16 at 13:19
  • `var` always returns `undefined`. Try it in console: `var a=5;`. `var a, b = 3` declare 2 variables, `a (not inited yet)` and `b (inited, =5)`. If you hate scopes, you can declare all variables at top of file: `var camera, scene, renderer, startTime, stats`. The comma is used to declare multiple variables in one `var` statement. –  Nov 22 '16 at 13:25

2 Answers2

2
var a, b = 3;

Is the same as the following:

var a;
var b = 3;

Variable declaration (the var keyword) is not an expression. The commas in variable declarations are more akin to the commas in function argument lists. They do not return anything.

It is true that the comma operator returns the last item, but I am not sure if it has any practical use cases (outside the for loop's initialization).

> 1, 2, 3
< 3

The page you linked to actually explains it pretty well.

Sverri M. Olsen
  • 12,362
  • 3
  • 32
  • 50
  • "Variable declaration (the var keyword) is not an expression" - well, `b = 3;` is also not an expression, it is an `ExpressionStatement`. It's not about expression or not, it's about what the spec says it should evaluate to. – lexicore Nov 22 '16 at 14:00
  • Question on the practical use of the comma operator: [When is the comma operator useful?](https://stackoverflow.com/questions/9579546/when-is-the-comma-operator-useful) – try-catch-finally Jul 22 '17 at 06:52
1

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).
lexicore
  • 39,549
  • 12
  • 108
  • 193
  • Yes, i check the document too. var a, b = 3 is VariableStatement which consist of keyword var and (a & b stand for VariableDeclaration) ,and number 1 is stand for expression. The EMCA document also say . A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created... for more detail , see https://www.ecma-international.org/ecma-262/7.0/index.html#prod-VariableStatement – Anson Hwang Nov 23 '16 at 13:35