Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name of this 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) ?

like image 292
Stephan Avatar asked Feb 16 '14 15:02

Stephan


2 Answers

Comma Operator: ,

The comma operator , has left-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:

  1. 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.

  2. 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?

like image 65
Grijesh Chauhan Avatar answered Oct 24 '22 10:10

Grijesh Chauhan


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.

like image 26
Mehran Hatami Avatar answered Oct 24 '22 08:10

Mehran Hatami