0

I'm very new in the JavaScript, but I found the syntax (0, myFunction)() to call anonymous functions on JavaScript, but I don't know what means the 0 before the anonymous function, also I don't know if instead of 0 I can use 1 or 2, etc.

Basically my question is what is the difference between call a function myFuntion() or (0, myFunction)(). The function is in a global context.

Here is an example.

var object = {}
object.foo = function(){}

The difference between call the function

(0,object.foo)();

or

object.foo();
JJJ
  • 32,902
  • 20
  • 89
  • 102
Jorge Alvarez
  • 293
  • 2
  • 4
  • 15
  • 1
    Please provide more context. `(0, myFunction)` by itself doesn't do anything (it certainly doesn't execute a function). – Felix Kling Jun 19 '14 at 17:57
  • Where did you see this? In what context? Can you post an example? – Dan Korn Jun 19 '14 at 17:57
  • You sure it had the outer parens? It makes a little more sense without them. – cookie monster Jun 19 '14 at 17:58
  • ...I assume you saw `(0, function() { /* some code */ }())`, but then the `0,` seems pointless. This however is a little different `0, function() { /* some code */ }()` – cookie monster Jun 19 '14 at 17:59
  • Or how about this: `"invoke"<-function() { /* some code */ }()` – cookie monster Jun 19 '14 at 18:02
  • With your edit of adding (), it just made it a little more clearer. Now you can read about the comma operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – epascarello Jun 19 '14 at 18:20
  • 2
    possible duplicate of [Indirect function call in JavaScript](http://stackoverflow.com/questions/5161502/indirect-function-call-in-javascript) – JJJ Jun 19 '14 at 19:24
  • The comma "operator" yields the last value which, in this case, is the function ... calling it will drop the `this` though. – Ja͢ck Jun 20 '14 at 16:19

1 Answers1

2

You can rewrite both calls into the following equivalents:

object.foo.call(null); // (0,object.foo)();

object.foo.call(foo); // object.foo();

As you can see, the only difference is the "binding" of this inside the called function; but the use of (0, something)(); is considered as cryptic and should be avoided in a professional code base.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309