3

I've seen this pattern a lot in javascript files:

(function ($) 
{
   //Perform operation X
}(jQuery));

Is there a difference between placing the above code in a js file vs the following:

function myFunc($) 
{
   //Perform operation X
}
myFunc(jQuery);

Or is it simply more terse?

C.J.
  • 6,789
  • 7
  • 36
  • 45

3 Answers3

5

Your second snippet defines a public symbol, myFunc. If anyone else is using that symbol for a library, you would overwrite it and could destroy its functionality. The first snippet doesn't have a name, and is therefore safer.

configurator
  • 40,828
  • 14
  • 81
  • 115
2

The only advantage the former has over the latter is that you aren't polluting the scope with the variable name (myFunc).

I.e. in the second example, if you already had a variable named myFunc in the same scope, its value would be overwritten by the function, where as in the first example, this wouldn't be the case.

Furthermore, the second example obviously allows you to invoke myFunc multiple times, where-as the first example permits it only once.

Matt
  • 74,352
  • 26
  • 153
  • 180
2

Firstly, I think your first code snippet should be:

(function ($) 
{
   //Perform operation X
})(jQuery);

And as far as I can tell, there is no difference between both codes except that the second one creates the function, stores it in a global variable and then calls it, whether the first one create an anonymous function and calls it right away.

Deleteman
  • 8,500
  • 6
  • 25
  • 39
  • The () can be done either way. JSLint prefers the parenthesis at the end, which is why I do it that way. – C.J. Oct 14 '11 at 13:03
  • You're right, this thread explains a bit more about this subject: http://stackoverflow.com/questions/3783007/is-there-a-difference-between-function-and-function – Deleteman Oct 14 '11 at 13:08