0

Should be easy question. I've recently started learning about these self-invoking functions and closures which keep private variables and it's kind of a mess in my head right now. I see people doing it in different ways, and I wonder, might this actually be the same thing?

(function(){})();

(function(){}());

As far as I understand it, the first one is a self-invoking expression of a function definition, whereas the second an expression of a self-invoking function definition. But is this correct, and what is the difference (in practice, technical or performance)? Are both of these (the same kind of) closure?

I'm an experienced programmer myself, so I would appreciate to know how this works. Thanks!

  • 1
    In general `a === (a)`. Hence `a() === (a)()` and `a() === (a())`, therefore `(a)() === (a())`. In other words: For all intends and purposes, both examples are equivalent. If you [inspect the ASTs for both examples](http://astexplorer.net/#/7zfbecOqud), they are identical. – Felix Kling Dec 15 '16 at 21:05
  • ok, thanks. so it just comes down to the order of making an expression and making an invocation, and that either way the result is the same. – Jack McKalling Dec 15 '16 at 21:16
  • I see that the ASTs differ slightly, as what is considered the CallExpression in both are different. – Jack McKalling Dec 15 '16 at 21:23
  • You mean when you mouse over the nodes? Sure, in the second case, the CallExpression cannot contain the parenthesis *around* it. However, that's just an AST node to source code mapping. The structure of the AST is still the same. Without the highlight and just looking at the AST, you wouldn't be able to tell the difference. – Felix Kling Dec 15 '16 at 22:20
  • Ok, thanks. So if they're the same, I think I'll just prefer the first notation then. That one makes the most sense to me when I look at it. – Jack McKalling Dec 15 '16 at 22:59

0 Answers0