Question

I'm looking to understand the difference between this code:

(function() {

and this code:

$(function() {

Does the first example run the code after document ready, as the second does? Or does it simply scope the function and nothing more?

Was it helpful?

Solution

The first example is a closure, it's a design pattern commonly used in JavaScript. In the second one you're calling the $ function giving another function as parameter (jQuery will execute it as soon as the document is ready, since it's an alias of $(document).ready(function () {})).

This is an example of closure:

(function () {
    var foo = 'foo';
    var bar = 'bar';
    window.foo = foo;
})();    // Those () mean that you're calling this anonymous function

console.log(typeof foo);    // Logs 'string'
console.log(typeof bar);    // Logs 'undefined', since 'bar' is internal to the closure's
                            // scope and was not exposed like was 'foo'

And this is an example of $(function () {}):

$(function () {
    alert('Document ready');
});

Check these pages:

OTHER TIPS

Your first example is just calling the anonymous function straight away, it allows you to do something like (demo):

(function(test) {
    alert(test);
})('asd')

Whereas the second example you've provided is a jQuery specific call which is run after the DOM is ready - it's essentially a shorthand for $(document).ready(function(){}); (see here)

The first approach, is using self executing anonymous functions.

  1. These methods are executed / called immediately.
  2. These are primarily used to prevent global scope / namespace.
  3. These are usually called once.

More info about self executing anonymous functions go through http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

The second approach, we are calling jQuery short version of the ready method.

There are three version of calling jQuery ready method ( Source: jquery api )

$( document ).ready( handler )
$().ready( handler ) (this is not recommended)
$( handler )

For More info about the jQuery ready method go through http://api.jquery.com/ready/

 (function() {

This javascript closure which is self executing anonymous function, runs immediately

 $(function() {

jQuery factory function which accepts function as a parameter and runs after DOM is ready

(function() {
    // Code goes here
}());

This is an "immediate function", meaning that is is executed immediately after it is defined. It is also an anonymous function in that it has no name.

This construct is used to provide a variable scope for the script that does not pollute the (usually) global namespace. This is commonly referred to as a "closure". Not polluting the global namespace is a good practice, as it prevents mixing up variable names and inadvertently messing with the operation of other scripts.

$(function() {
    // Code goes here
});

This is a shorthand for jQuery's $(document).ready(function() { /* code goes here */ }). It executes the code within only when the entire DOM has been rendered, and is considered ready. Usually you can just omit this if your script is inserted at the very end of the <body>.

The first would typically run the code immediately, but only because of the code you have not shown, at the end of the anonymous function definition. It would be invoked because of:

(function() { doSomething(); } ());

Note this runs immediately, NOT after the document is loaded. The trailing empty parens invoke the function, with zero parameters, just as when you call myFunction(). It is typically written this way just to "scope" variables. For example, you may wrap your entire javascript file like this to protect it from other included files.

In the second example, the $ is actually a function. It is a synonym for "jQuery", so $() is just like jQuery(). jQuery actually also runs this function immediately, with the anonymous function definition as the parameter. What jQuery IMMEDIATELY DOES when you pass it a function definition like this, is queue that function definition to run when the document ready event fires.

The first:

(function() {

Is for self-invoking function (an anonymous function that call itself), like:

(function(){  // some code… })(); 

The Second:

$(function() {

Is an jQuery specific DOM ready event handler function, like the jQuery $(document).ready function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top