Javascript "tuple" notation: what is its point?

Grilse picture Grilse · Jan 26, 2012 · Viewed 12.4k times · Source

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?

Answer

Rich O'Kelly picture Rich O'Kelly · Jan 26, 2012

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).