What you have encountered is the comma operator.
When there is no other context, a ,
in an expression behaves like an operator just like +
or =
or /
etc.
The comma operator behaves as follows:
- evaluate the first expression
- ignore the result of the first expression
- evaluate the second expression
- return the value of the second expression
Thus the following code:
a = 1,2;
b = 1,2,3,4;
will result in a
being assigned the value 2
and b
assigned the value 4
.
This may seem kind of silly because we already have ;
but the comma operator is useful if you need more than one thing to happen in a single expression context. For example if you need more than one thing to happen in one of the conditions of a for
loop you cannot use ;
because that is used to separate the conditional expressions. The comma operator comes to the rescue:
for (let a = 0, b = 0; a < 10; a++, b++) { //...
// ^ ^
// | |____ two things happen here
// |_______________________________ and here
So (1,2)
is just another way to write 2
.
Therefore [(1,2) , (3,4) , (5,6)]
and [2,4,6]
is the same array.
Just like [1+1, 2+2, 3+3]
and [2,4,6]
is the same array.
They are just different ways to write [2,4,6]
. The same way you cannot loop through the array and extract 1+
from [1+1, 2+2, 3+3]
you cannot loop through the array and extract (1,
from [(1,2) , (3,4) , (5,6)]
.
If you really need an array of pairs you need to use an array of arrays:
a = [[1,2],[3,4],[5,6]]