Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the result of two function definitions joined by a comma?

Why does the following code alert 2?

var f = (function x(){ return 1; }, function y(){ return 2; })();
alert(f);

What I can see is that somehow the y function is getting executed and x function is ignored. (I have made sure that I put alert in both functions, and only the alert in y is called which make me believe that the x function is not being called at all)

And if I remove the y function then it alerts 1.

What's going on?

like image 804
PHP Avenger Avatar asked Apr 04 '13 21:04

PHP Avenger


2 Answers

Ok, let's break it down a little.

(function x(){ return 1; }, function y(){ return 2; })

Is two function literals.Next the comma operator is used. It evaluates the expressions (both functions) and returns the last one. the result of this expression is: function y(){ return 2; }

Which means the remaining expression is: var f = (function y(){ return 2; })();

The next thing we do is call it (with the ()) which returns 2 into the variable f;

like image 117
Benjamin Gruenbaum Avatar answered Oct 23 '22 08:10

Benjamin Gruenbaum


When you use the comma operator, the returned value is that of the last element, in your case, the function y() (which returns 2)

From the mozilla docs:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

like image 30
Nelson Avatar answered Oct 23 '22 08:10

Nelson