Comma Operator:,
The comma operator has left-to-right associativity . Two expressions, separated by commas, are evaluated from left to right. The left operand is always evaluated, and all side effects are completed before the operand is evaluated.
Expression:
var myVar = (12, 5);
is equivalent to:
var myVar = 5;
Note that in the bracket above the expression overwrites the priority , over = , otherwise without parentheses an expression like var myVar = 12, 5 is equivalent to var myVar = 12 .
Edit: There may be the following reasons why I think you will find this expression:
When the first expression has some side effects:
var myVar = ( expression1, expression2);
expression1 may have some side effects that may be required earlier to appropriate the result of expression2 myVar , for example. var mayVar = (++i, i + j); In this expression, the incremented value after ++i will be added using j , and the result will be assigned to mayVar .
Bug fixed or bug:
Maybe some bug fixes or during testing instead of assigning x developer wanted to assign y , but forgot to delete ( ) before being published.
var myVar = (x, y);
I also found a typo in which the questioner forgot to write the same function and instead of writing
var myVar = fun(x, y);
his typo:
var myVar = (x, y);
In a related question .
This is not a JavaScript link, but a very interesting C ++ link that discussed the legal / or possible use of comma operators. What is the correct use of the comma operator?
source share