JavaScript / jQuery closure function syntax


(function($){
  // can do something like 
  $.fn.function_name = function(x){};

})(jQuery);

That is self-executing anonymous function that uses $ in argument so that you can use it ($) instead of jQuery inside that function and without the fear of conflicting with other libraries because in other libraries too $ has special meaning. That pattern is especially useful when writing jQuery plugins.

You can write any character there instead of $ too:

(function(j){
  // can do something like 
  j.fn.function_name = function(x){};

})(jQuery);

Here j will automatically catch up jQuery specified at the end (jQuery). Or you can leave out the argument completely but then you will have to use jQuery keyword all around instead of $ with no fear of collision still. So $ is wrapped in the argument for short-hand so that you can write $ instead of jQuery all around inside that function.


(function(){

}());

That is self-executing anonymous function again but with no arguments and runs/calls itself because of () at the end.

That patterns turns out to be extremely useful in some situations. For example, let’s say you want to run a piece of code after 500 milli seconds each time, you would naturally go for setInterval.

setInterval(doStuff, 500);

But what if doStuff function takes more than 500 mill-seconds to do what it is doing? You would witness unexpected results but setInterval will keep on calling that function again and again at specified time irrespective of whether doStuff finished.

That is where that pattern comes in and you can do the same thing with setTimeout in combination with self-executing anonymous function and avoid bad setInterval like this:

(function foo(){
   doStuff;

   setTimeout(foo, 500);

})()

This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using bad setInterval.

You can test it here.

Note that you can also write self-executing anonymous function like this:

function(){
  // some code
}();

Using extra braces around (like before function keyword) is simply coding convention and can be seen in Crackford’s writings, jQuery and elsewhere.


$(function(){

});

That is short-hand syntax for ready handler:

$(document).ready(function(){

});

More Information:

Leave a Comment