jquery anonymous function declaration meanings

Are the following assumptions accurate?

1) execute immediately

(function(){
})();

2) execute on document ready

$(document).ready(function(){
});

3) shorthand for on document ready

$(function(){
});

4) alternative shorthand for on document ready for avoiding cross script conflicts

(function($) {
})(jQuery);

Yes your definitions are correct, for the first 3 🙂

Though, unless you need a closure, a statement will execute immediately, no reason to wrap it like #1 has (there are certainly plenty of valid times you need a closure, just noting if you don’t…it’s superfluous).

Number 4 however is not correct, (function($) { })(jQuery); is not tied to any event, it’s just a closure so that $ === jQuery inside of it, so you can use the $ shortcut:

(function($) { 
  //You may use $ here instead of jQuery and it'll work...even if $ means
  //something else outside of this closure, another library shortcut for example
})(jQuery);

Here’s the #4 you were looking for:

jQuery(function ($) {
});

It will run on document.ready, within a namespace, and with jQuery defined as $.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Array.length vs arrayinstance.length in javascript

Similar Posts