0

What is going on in this Javascript code? Is there a name for this or some place to learn more about the specific behavior illustrated?

I didn't think coding a "tuple" in JS would be valid syntax, but it seems to be. However the resulting variable definitely doesn't behave as a tuple, which is expected given JS's lack of support for them.

It's behavior seems very odd to me though.

It only gets 1 of the two values stored into it, and strangely removing the parenthesis is still valid javascript but ends up storing the opposite value into the varible

-> x = (90, 27);
<- 27
-> x
<- 27

-> x = 90, 27;
<- 27
-> x
<- 90
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • Does this answer your question? [What does the comma operator do in JavaScript?](https://stackoverflow.com/questions/3561043/what-does-the-comma-operator-do-in-javascript) – jonrsharpe Oct 12 '22 at 20:35

3 Answers3

3

Comma operator returns the last element

No tuples in JavaScript

Konrad
  • 21,590
  • 4
  • 28
  • 64
3

It is just javascript evaluating expression, when you have parenthesis () javascript will evaluate the whole expression inside the parenthesis first and then assign it to the variable since x = (1,2) 2 is the last evaluated value will be assigned to x. But if you don't have parenthesis then it evaluates step by step expression x = 1,2 the first expression it finds is x=1 and then just evaluates 2 it's as if you typed x=1; 2;

Endrit
  • 91
  • 3
1

That's not a tuple. JavaScript does not have tuples. You're simply doing

x = 90, 27

but wrapping the expression 90, 27 in parentheses. The reason why it's returning 27 is because that's the last element.

Michael Moreno
  • 947
  • 1
  • 7
  • 24