0

Is there any differences between javascript modules:

(function(){}())

vs

(function(){})()

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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
st1
  • 661
  • 1
  • 6
  • 12
  • 1
    How is it related to design-patterns? – thefourtheye Dec 20 '13 at 14:05
  • exact duplicate of both [Location of parenthesis for auto-executing anonymous JavaScript functions?](http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions) and [(…()) vs. (…)() in javascript closures](https://stackoverflow.com/questions/8774425/vs-in-javascript-closures) – Bergi Dec 20 '13 at 14:34
  • I thought that module pattern is a design pattern (wiki says that) – st1 Dec 20 '13 at 14:54
  • Sorry for duplicates. Wasn't able to find it by code example. – st1 Dec 20 '13 at 14:57

3 Answers3

1

There is no different. Also you can write the third option if your function doesn't return any value

!function(){}()
kmakarychev
  • 731
  • 4
  • 14
0

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

tewathia
  • 6,890
  • 3
  • 22
  • 27