1

What is the difference between function($) and $(function())?

Is this code redundant?

(function($) {
    "use strict"; 

  $(function() {
      run_code();
  });

})(jQuery); 

Are they both document ready functions?

user2012677
  • 5,465
  • 6
  • 51
  • 113
  • 3
    The first one is an IIFE that takes jQuery as a parameter to protect code inside from the global `$` variable being overwritten. The second is using jQuery. – VLAZ Oct 24 '19 at 18:24
  • Is is redundant? Is function($) a document ready function like $(function())? – user2012677 Oct 24 '19 at 18:25
  • 2
    As for "redundant" it's hard to say. It's a defensive coding technique that *might* be unneeded but it's super cheap and at worse adds few characters without harming much. – VLAZ Oct 24 '19 at 18:26
  • 1
    The outer wrapper probably serves to protect that JavaScript from potentially hostile third-party JavaScript that may seek to redefine `$` arbitrarily. – tadman Oct 24 '19 at 18:27
  • 1
    [it's an IIFE](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) not a document ready function - it will be executed ASAP. – VLAZ Oct 24 '19 at 18:27

1 Answers1

3

They may look similar, but they are completely unrelated.

This is called an Immediately Invoked Function Expression (IIFE). These are not specific to jQuery, but in this case, it ensures that within the body of this function, $ will refer to jQuery, even if something outside the function has overwritten the global $ variable with something else. It is a defensive practice for minimizing conflicts with other libraries.

An additional benefit is that any variables declared within this function will not be added to the global scope. Even without jQuery, this is a common practice used to help modularize code and avoid polluting the global scope.

(function($) {
    "use strict"; 


})(jQuery); 

This tells jQuery to execute the specified function when the DOM is "ready":

$(function() {
    run_code();
});
JLRishe
  • 99,490
  • 19
  • 131
  • 169