How to print JavaScript array with set of pairs inside array

Viewed 466

I was going through documentation of JavaScript about arrays and objects.I found one unique query about arrays

var a= [1,2,3]
console.log(a)     // give [1,2,3]


var b = [(1,2) , (3,4) , (5,6)]
console.log(b)     // gives [2,4,6]

I didn't understand the logic behind the same.It just ran over my mind.If we do same thing in python

a = [(1,2),(3,4)]
print(a)     // [(1,2),(3,4)]

Can some one explain the same and can someone explain me how to get the same output in JavaScript like the way I got in python.How to iterate through all the elements in array in javascript

2 Answers

I'm not a Python programmer, but those parentheses differ in their functionality between Python and JavaScript.

I understand in Python they indicate a tuple literal. In JavaScript, they merely group things they say "execute each statement and return the last one." That's why you only see some items in your JS arrays.

See also https://stackoverflow.com/a/25280412/1371131

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]]
Related