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