javascriptjqueryanonymous-functioniife

What is this unknown JavaScript syntax?


Is this jQuery code

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

equivalent to

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

If yes, what are the differences between the two? If not, what does the first do?


Solution

  • Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.

    (function(jQuery){
      //jQuery in this scope is referencing whatever is passed-in
    })(jQuery);
    

    So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.

    Take this example:

    (function(obj) {
       alert(obj);
    })('Hello');
    

    This defines a function, then immediately invokes it, passing in "Hello"