Search code examples
javascriptmodule-pattern

javascript module pattern implementations


Is there any differences between javascript modules:

(function(){}())

vs

(function(){})()

First from book "good parts" by Crockford. Second is code generated with Typescript.


Solution

  • No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.

    The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.

    But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.