Search code examples
javascriptjquerydocument-readydeferred-execution

Meaning of (function(){ in Javascript


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?


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: