What is the name of this syntax "(x, y)"?

I recently read javascript code and I came across this line:

var myVar = (12,5); // myVar==5 now 

What is this weird syntax: (x, y) ?

+6
source share
3 answers

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?

+7
source

it is called Comma Operator, we usually use them when we want to run operator 2 in one expression, it evaluates 2 operands (from left to right) and returns the value of the second.

check it out here: comma operator

And read this question if you want to know where it is useful.

+1
source

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. 
0
source

All Articles