Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "tuple" notation: what is its point?

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?

like image 735
Grilse Avatar asked Jan 26 '12 12:01

Grilse


People also ask

What is a tuple in JavaScript?

Tuples are a sort of list but with a limited set of items. In JavaScript, tuples are created using arrays. In Flow you can create tuples using the [type, type, type] syntax.

What is use of tuple in TypeScript?

A tuple is a TypeScript type that works like an array with some special considerations: The number of elements of the array is fixed. The type of the elements is known. The type of the elements of the array need not be the same.

What is the difference between tuple and array in TypeScript?

The structure of the tuple needs to stay the same (a string followed by a number), whereas the array can have any combination of the two types specified (this can be extended to as many types as is required).

How do you initialize a tuple in TypeScript?

var mytuple = [10,"Hello"]; You can also declare an empty tuple in Typescript and choose to initialize it later.


2 Answers

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

like image 177
Rich O'Kelly Avatar answered Sep 22 '22 13:09

Rich O'Kelly


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 ",,,".

like image 26
dfsq Avatar answered Sep 21 '22 13:09

dfsq