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)
?
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)
?
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.
This is called the comma operator.
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
Here are some examples:
var a = (12,3) //a =3;
var b = (a+2, 2) //a=5, b= 2
var c = (a,b) // a= 5, b=2, c=2.