0

I recently discovered that (1,2) equals 2

Same for (1,3,4) => 4 always return the last number

What is this expression exactly? It's not an array, not an object, what is it ?

walox
  • 567
  • 1
  • 7
  • 26
  • Because of this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Gerardo Furtado Apr 04 '19 at 12:16
  • It's the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) – Pointy Apr 04 '19 at 12:16
  • 1
    *"The [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) evaluates each of its operands (from left to right) and **returns the value of the last operand**"* – adiga Apr 04 '19 at 12:17

1 Answers1

1

Code within parentheses is evaluated as an expression. Several expressions can be grouped together by using a comma. Commas are not just syntax for dividing arguments or function parameters, they double as an operator - much like +, -, etc serve multiple purposes, so does ,

In the case you've outlined (1,2) the grouped expressions are obviously 1 and 2. They are both evaluated to themselves, but when expressions are grouped by comma operators, only the last evaluated expression is returned.

This means:

(1,2) == 2

and:

(1,2,3,4) == 4

zfrisch
  • 8,474
  • 1
  • 22
  • 34