28

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

var foo = function(){alert("hello?")};
(0,foo)();
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
Funky Oordvork
  • 403
  • 4
  • 15
  • 4
    @ubercooluk – There is no sign of jQuery there at all. – Quentin Jan 09 '13 at 10:44
  • 2
    @Alex — No, it isn't. There are no variables being enclosed. Are you confusing a function expression with a closure? Function expressions are often used to create closures, but they are not the same thing. – Quentin Jan 09 '13 at 10:44
  • 2
    @Funky, are you sure `foo` is defined this way and is not an object method (`(0, obj.foo)()`)? The call semantics will not be the same if this is the case. – Frédéric Hamidi Jan 09 '13 at 10:48

4 Answers4

38

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
Kos
  • 70,399
  • 25
  • 169
  • 233
  • 7
    (The comma operator also has the undocumented feature of causing funny bugs when someone makes a typo.) – Kos Jan 09 '13 at 10:56
  • Thanks @Kos, your explanation makes sense. The snippet is based on code from a complex and well written 3rd party tool and yet it is overly complex. I assume maybe the 0 used to be something more substantial which was replaced by the 0 as a placeholder ? – Funky Oordvork Jan 09 '13 at 11:11
  • 2
    Or the right side may have been replaced. (0,eval)() is a way of calling indirect evals, which are used to protect global scope http://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript – Ben McCormick Jan 09 '13 at 16:50
9

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

Dziad Borowy
  • 12,368
  • 4
  • 41
  • 53
2

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.

Moritz Roessler
  • 8,542
  • 26
  • 51
1

the comma will evaluate operands and return the last one

the second line will return foo