9
; (function ($, undefined)
{

    // all the variables and functions of the js document

})(jQuery);

I've seen this twice now in the jquery/javascript files for a zoom script. I don't understand what this is exactly. I can't seem to google it, I don't remember coming across this on tizag or w3schools while recently learning jquery and js.

There's nothing before or after this code (other than some comments). So I'm utterly lost as to what (function())(jQuery); is or does.

Matt
  • 70,063
  • 26
  • 142
  • 172
Eric
  • 1,856
  • 4
  • 20
  • 32
  • 1
    Pretty much everything will be clear after reading this: http://james.padolsey.com/javascript/iife-argument-madness/ – romainberger Apr 19 '13 at 12:51

2 Answers2

8
(function ($, undefined)
{

    // all the variables and functions of the js document

})(jQuery);

calls a block of code ensuring that inside

  • $ is usable to refer to jQuery
  • undefined is undefined

and that any minifier can change undefined to a shorter label.

The initial ; ensures you can concatenate this file with another one : without this, you'd have an error executing the concatened file if the one just before was something like

(function (){

})()
Matt
  • 70,063
  • 26
  • 142
  • 172
Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
5

This is a way to ensure that $ is indeed the jQuery object and to ensure that any local variables and methods are privately scoped, that is, do not pollute the global namespace.

It is a self-calling anonymous function, with the parameter passed being jQuery, meaning that the $ will be the jQuery object.

Being declared inside a function means that the inner variables and methods will not be visible outside of it.

Oded
  • 463,167
  • 92
  • 837
  • 979
  • 5
    Also - The semi-colon in the beginning is just a safety measure in case this code were to be included after some other JS without proper formatting. – Collin G. Apr 19 '13 at 12:52