29

At wtfjs, I found that the following is legal javascript.

",,," == Array((null,'cool',false,NaN,4)); // true

The argument (null,'cool',false,NaN,4) looks like a tuple to me, but javascript does not have tuples!

Some quick tests in my javascript console yields the following.

var t = (null,'cool',false,NaN,4); // t = 4
(null,'cool',false,NaN,4) === 4; // true
(alert('hello'), 42); // shows the alert and returns 42

It appears to behave exactly like a semicolon ; separated list of statements, simply returning the value of the last statement.

Is there a reference somewhere that describes this syntax and its semantics? Why does it exist, i.e. when should it be used?

Grilse
  • 3,491
  • 2
  • 28
  • 35
  • It is the comma operator: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/ – Lepidosteus Jan 26 '12 at 12:49
  • 1
    The comma operator can also be (ab)used to run a series of functions inside of a ternary branch, as it will return the result of the last statement anyway: `var a = isTrue ? (b=f(c), g(b)) : (b=g(c), f(b))`. Rarely wise, but sometimes useful if very concise code is preferred over readability, or for quick debugging purposes. – okdewit May 22 '15 at 09:58
  • This is called an 'expression' in JavaScript, this is not simply an effect of the comma operator though it plays a small part; This expression is resolved because of the comma operator. You can set a value to any mutable variable of any evaluated expression. Even if that expression is undefined. – Eric Hodonsky Aug 18 '17 at 20:36

3 Answers3

37

You are seeing the effect of the comma operator.

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

The resultant value when a,b,c,...,n is evaluated will always be the value of the rightmost expression, however all expressions in the chain are still evaluated (from left to right).

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
8

As already explained this behaviour is caused by , operator. Due to this the expression (null,'cool',false,NaN,4) will always evaluate to 4. So we have

",,," == Array(4)

Array(4) - creates new array with allocated 4 elements. At the time of comparison with the string this array is converted to string like it would be with Array(4).toString(). For arrays toString acts like join(',') method called on this array. So for the empty array of 4 elements join will produce the string ",,,".

dfsq
  • 191,768
  • 25
  • 236
  • 258
2

Try this alert((null,'cool',false,NaN,4)) and then you can see.

demo

The reason is because the comma operator evaluates all the statements and return the last one.

Think of this line: a = 1, b = 2, c = 3; it will run each expression so in essence it will set the variables to what you want and return the last value (in this case 3)

qwertymk
  • 34,200
  • 28
  • 121
  • 184