Funky Oordvork
Funky Oordvork

Reputation: 403

Why would a function-call expression use a comma-operator expression as the function to be called?

could someone please explain to me what is going on in the second line here ? :

var foo = function(){alert("hello?")};
(0,foo)();

Upvotes: 28

Views: 890

Answers (4)

user1960990
user1960990

Reputation:

the comma will evaluate operands and return the last one

the second line will return foo

Upvotes: 0

Kos
Kos

Reputation: 72221

The infamous comma expression a,b evaluates both arguments and returns the value of the right-hand expression.

Hence in this case it's exactly the same as foo();.

Here's a better example that will help you understand what's going on:

function foo() {
    print("foo called");
    return 123;
}
function bar() {
    print("bar called");
    return 456;
}
var result = (foo(), bar());
print("result:", result);

Output:

foo called
bar called
result: 456

Also the comma expression may be confused with the comma delimiting function arguments. Not the same! Notice the difference:

print("result:", foo(), bar() ); // 3 arguments, no comma operator
print("result:", (foo(), bar()) ); // 2 arguments, comma operator

Upvotes: 38

Moritz Roessler
Moritz Roessler

Reputation: 8611

Since the Comma operator in javascript evaluates multiple operands and returns the last one. MDN:

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

Your expression (0,foo)

returns foo which then is invoked by the paranthesis, put after it.

Upvotes: 1

Dziad Borowy
Dziad Borowy

Reputation: 12579

It's evaluating both expressions in the first parenthesis and executing the second one (in this case - a function).

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comma_Operator

Upvotes: 9

Related Questions