Immediately invoked function expression aka IIFE

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: