I want expand my last post (Immediately invoked function expression aka IIFE), by more examples of using IIFE.

IIFE can be also used like this:

var foo = function() {
// code
}();

However, it’s better practice to do this like this, because of code readability:

var foo = (function() {
// long code
})();

If you have on your page jQuery and maybe other JS library that uses $ sing to access it. You may use this little pattern to pass library to IIFE, the way it will not make conflicts. And also get advantage of $ access to that library:

(function($) {
// code using $
})(jQuery);

Also it helps with rendering animations:

(function animation_loop() {
    window.requestAnimationFrame(animation_loop)
    render():
})();

It’s protect against unwanted globals:

(function() {
     window.public = 'foo';
     var private = 'bar';
})();

// latter on

public; // foo
private; // undefined

Useful if you want compute and return value in one statement:

var browser = {
    vendor_prefix : (function() {
        var prefix;
        // compute stuff
        return prefix;
    })()
};

Create a class in one statement:

var MyClass = (function() {
    function MyClass(foo) {
        this.foo = foo;
    }

    MyClass.prototype = {
        bar : 'baz'
    };

    return MyClass;
})();

Creating private variables:

var number = (function() {

    var num =0,
    add = function(n) { num = num + n;},
    get = function() { return num; };

    return { add:add, get:get};
})();

create private functions:

var foo = (function() {
    var priv = function() { alert('Hi'); },
        publ = function() { priv(); }

    return publ;
})();

Sources:

This time I want show you something interesting from jQuery source code:

(function( window, undefined ) {

})( window );

It’s called immediately invoked function expression aka IIFE. Called also, but these names are are a little bit incorrect:

  • self executing anonymous function
  • self invoking anonymous function

Advantages of using this pattern are:

  • In ECMAScript 3 undefined variable is mutable. And as a result of it, you can change it’s value which can lead to bad comparison results. When you will need compare for example:  foo === undefined. Using this pattern you guarantee, that undefined variable in scope of this self executing anonymous function got correct value. Independently of earlier changes of this variable.  This was achieved by not passing while executing undefined value to function body by parameters. In this way undefined in scope of function is “really” undefinded. It’s weird, but it works :)
  • little better performance, because of fasten identifier resolution process
  • better compression, because compressor can change window variable to single letter, and thus is able to save some byes
  • protecting against unwanted globals from leaking
  • Allow you compute and return value when only one statement is allowed
  • Require to emulate block scope (pre E6’s ‘let’)
  • useful when creating private functions and variables using closures

Newer and considered better version of this pattern is:

(function(window, document, undefined){

})(window, document)

It’s better than above solution, because has all it advantages, but benefits of compression and performance also apply to document variable.

At end, I want say a bit about, from where this pattern comes from. It comes from what is called IIFE

(function() {

})(); // <-- brackets immediately invoke function

This code simply create new function expression and immediately invoke, run it using () at end.

Same way will work these examples:

!function() {

}();
+function() {

}();
-function() {

}();
~function() {

}();
new function(arg) {

}(arg);
(function() {

}).call();

 

All solution will work the same way in all browsers, we using () insead of !,+ or other. Because this  is simply a convention.

Interesting materials about this topic: