2

Due to a typo I made today, I started messing around with my node repl and am trying to figure out why this is happening on my machine both in Chrome and Node (v6.9.2).

> 1, 2, 3, 8
8
> a = 1, 2, 3, 8
8
> a
1
> (1, 2, 3, 8).toString()
'8'

What is the javascript engine seeing/parsing/doing here? I can't help but feel confused by what's going on and would appreciate some direction on where I can go to learn more about it.

Droogans
  • 6,701
  • 5
  • 36
  • 60
  • 3
    a comma is like a semicolon, only it concatenates multiple statements as one. you're assigning the number 1 to `a`, and then following it with separate statements of numbers which dont do anything. – I wrestled a bear once. Dec 09 '16 at 21:31
  • 1
    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Rocket Hazmat Dec 09 '16 at 21:32

1 Answers1

5

It's the comma operator , that's doing its magic here. expr1, expr2 will evaluate both expressions, but return only the latter.

If expr1 has no side effects, then the comma operator is really not very useful, as it will be functionally the same as just expr2:

var a = (2, 3); // 2 and 3 are both evaluated, but final result is 3; no side effects
var b = 3;    // functionally equivalent to the above

Where it makes a difference is when expr1 has side effects, such as calling a function, or changing a variable:

var a = 0, b = 3;
var c = (++a, ++b); // ++a has the side effect of incrementing a

var d;
d = 5, 6;     // (d = 5) has the side effect of setting d to 5

// now a = 1, b = 4, c = 4, d = 5

One case where this is useful is when you have a for loop with two simultaneous variables that you want to increment:

for(let i = 0, j = 5; i < 3; i++, j++) {
                          // `------´  comma expression, so both are incremented
  console.log(i, j);
}

// prints:
//   0 5
//   1 6
//   2 7

Note also that the comma operator is different from the statement separator ;, so the following won't work as expecte


Frxstrem
  • 30,162
  • 8
  • 66
  • 99