5

What is the difference between

$(function() {
    // bind some event listeners
});

and

$(function() {
    // bind some event listeners
}());
Aram810
  • 619
  • 7
  • 21

4 Answers4

2
$(function() {
    // bind some event listeners
});

In above case the function is passed to the jquery which will get executed once document is ready.

$(function() {
    // bind some event listeners
}());

In above case the return of the function is passed to the jquery. Since the function is se3lf executing itself, it will get executed immediately and whatever the function returns will get passed to the jquery, so this is not a good way because the objective is to execute the function once document gets ready which is not happening in this case

Saurabh Verma
  • 1,534
  • 1
  • 14
  • 28
1
$(function(){...}); OR $(document).ready(function(){ ... });

This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.

(function(){ ... })();

That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your JavaScript. Therefore, its very unlikely that you can successfully act on DOM elements here.

haMzox
  • 2,073
  • 1
  • 12
  • 25
1
$(function() {
    // bind some event listeners
});

This one will be executed only when the DOM is fully loaded, it's the shortcut for :

$(document).ready(function(){
  // Write code here
}); 

$(function() {
    // bind some event listeners
}());

This one is the same but the function inside the $() is a self invoking function. Usually the goal is to prevent variable name conflicts, because it's creating a new scope.

Allan Raquin
  • 583
  • 7
  • 26
1
$(function() { ... });

is just jQuery short-hand for:

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

Immediately-invoked function expression (or IIFE), instead, are expression "immediately executed", the convention is to enclose in parentheses, but every kind of expression is executed immediately, see following IIFE functions:

(function() {
    console.log("IIFE 1");
}());

+function() {
    console.log("IIFE 2");
}();

1-function() {
    console.log("IIFE 3");
}();

var f = 50 * function() {
    console.log("IIFE 4");
}();

I hope it was clear, bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70