I recently read a javascript code and I came across this line:
var myVar = (12,5); // myVar==5 now
What is this strange syntax : (x, y)
?
Comma Operator:
,
The comma operator
,
hasleft-to-right associativity
. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.
The expression:
var myVar = (12, 5);
is equivalent to:
var myVar = 5;
Note, in above expression parenthesis overwrites precedence of ,
over =
, otherwise without parenthesis an expression like var myVar = 12, 5
is equivalent to var myVar = 12
.
Edit: There can be following reasons I guess that you find this expression:
When first expression has some side-effects:
var myVar = ( expression1, expression2);
The expression1
may have some side effects that may required before to assign the result of expression2
to myVar
, e.g. var mayVar = (++i, i + j);
In this expression incremented value after ++i
will be added with j
and result will be assigned to mayVar
.
Bug fixed or bug:
May be some bug fixing/or during testing instead of assigning x
developer wanted to assign y
but forgot to remove (
)
before public relies.
var myVar = (x, y);
I also find a typo-bug in which questioner forgot to write function same and instead of writing
var myVar = fun(x, y);
his typo:
var myVar = (x, y);
In the linked question.
This is not JavaScript link but very interesting C++ link where legitimate/or possible use of comma operators was discussed What is the proper use of the comma operator?
it is called Comma Operator, we usually use them when we want to run 2 statement in one single expression, it evaluates 2 operands (left-to-right) and returns the value of the second one.
check it here: comma operator
And read this question if you want to know where it is useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With