0

I can use the comma operator in JavaScript to evaulate more than one expression and return the last one.

x = "foo", "bar"; // "bar"
y = 0, 21, 42; // 42

but why are parenthesis crucial if a function application is involved?

arr = [1,2,3];
z1 = (arr.push(4), arr); // [1,2,3,4]
z2 = arr.push(5), arr; // 5 ??

Why does the last statement set z2 to 5 instead of arr? How is this different to the previous to the previous statement that sets z1 correctly?

muffel
  • 7,004
  • 8
  • 57
  • 98
  • 1
    Just an observation - the final 5 is the length of the array, rather than the value you've pushed in. – James Thorpe Aug 07 '15 at 08:33
  • I cannot reproduce what you're seeing. There's a difference between the values of the variables and what the expression as a whole returns, i.e. what you would see in the console when typing these commands as is. Your last line returns `[1,2,3,4,5]` on the console. All other lines also show what is being returned on the console. The value of the variables is in no other case what you have annotated. I.e., your last line is inconsistent with the rest of the examples in terms of the test method, not in terms of Javascript's evaluation. – deceze Aug 07 '15 at 08:38
  • I don't know about your javascript engine, but Firefox (latest) assigns `foo` to `x` for `x = "foo", "bar"`. – Ejaz Aug 07 '15 at 08:39

1 Answers1

7

As the resource you've linked states:

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

From left to right, here is what your structure looks like:

  1. z2 = arr.push(5)
  2. arr

Due the the lack of parenthesis, z2 = arr.push(5) is a separate statement from arr and is executed first, then arr is executed (and returned). z2 is equal to 5, but the return from the entire line is [1,2,3,4,5]. Here is a screenshot of the code entered into a JavaScript console:

Example

z1 is equal to [1,2,3,4] because of the parenthesis. arr.push(4) is executed, then arr is executed and returned to the z1 variable.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • 2
    Another example from the OP - while `y = 0, 21, 42;` evaluates to `42` on the console, `y` is actually `0`. – James Thorpe Aug 07 '15 at 08:35
  • Yes, but the key point would seem to be the relative **precedence** of `,` vs. `=`. –  Aug 07 '15 at 08:36
  • With less words, you could write that `z2 = arr.push(5), arr;` is equivalent to `( z2 = arr.push(5) ) , ( arr );`. I think it might be clearer ? – Robin Nicolet Aug 07 '15 at 08:40