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:

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

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:

Also it helps with rendering animations:

It’s protect against unwanted globals:

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

Create a class in one statement:

Creating private variables:

create private functions:

Sources:

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

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:

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

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

Same way will work these examples:

 

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: