self executing function jquery vs javascript difference

As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.

The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.

(function (doc, win, $, myModule) {
    // Code
}(document, window, jQuery, window.MYAPP.myModule));

doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this

(function (doc, win, $, myModule) {
    // Code
}(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule

In all cases you are doing an anonymous function. I think 1 is the same as 2. In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.

For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.

(function ($) {
    //Here jQuery is $
    var Book = $(document.body).text();    

})(jQuery);

//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();

Immediately-invoked function expressions (IIFE) is one of the core JavaScript features. Its main aim is not to clutter the namespaces with disposable functions and variables.

if you use a variable or a function only once, you don't need to make it available for the rest of the code (therefore you make a private access, for example). In case of functions, you may just let them be anonymous, just like the following:

(function(){
  console.log("Hello symfony world!");
}());

Please check with this link

Furthermore here is a useful explanatory video in less than 7 minutes


This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {
   $(function () { // Here in this block you can use '$' in place of jQuery
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.