Immediately Invoked Function Expressions

Excerpt from JavaScript: Novice to Ninja

Immediately Invoked Function Expressions

An Immediately Invoked Function Expression (or IIFE, pronounced “iffy”) is a function that, as the name suggests, is invoked as soon as it’s defined. This is easily achieved by placing parentheses at the end of the function definition (remember that we use parentheses to invoke a function). The function also has to be made into an expression, which is done by placing the whole declaration inside parentheses, as can be seen in this example:

(function(){
  var temp = "world";
  console.log("Hello " + temp);

}());
<< "Hello world"

IIFEs are a useful way of performing a task while keeping any variables wrapped up within the scope of the function. This means that the global namespace is not polluted with lots of variable names.

Temporary Variables

There is no way to remove a variable from a scope once it’s been declared. If a variable is only required temporarily, it may cause confusion if it’s still available later in the code. Even worse, the name of the variable may clash with another piece of code (an external JavaScript library, for example) resulting in errors. Placing any code that uses the temporary variable inside an IIFE will ensure that it’s only available while the IIFE is invoked, and then it will disappear. The example that follows uses an IIFE to swap the value of two global variables, a and b. This process requires the use of a temporary variable, called temp, which only exists while the IIFE is invoked:

a = 1;
b = 2;
(function(){
  var temp = a;
  a = b;
  b = temp;
}());

console.log(a);
<< 2

console.log(b);
<< 1

console.log(temp);
<< Error: "temp is not defined"

Mimicking Block Scope

In most other languages, a variable has scope inside a code block―that’s what’s known as block scope. But this does not happen in JavaScript; variables only have a limited scope inside functions. This means that when a temporary variable is created inside an if block or a for loop, the variable will still be available outside of that block:

var list = [1,2,3];
for (var i = 0, max = list.length ; i < max ; i++ ){
  console.log(list[i]);
}
console.log(i); // i is still available outside the for block
<< 1
<< 2
<< 3
<< 3

The solution to this is to place the for block inside an IIFE to mimic block scope:

var list = [1,2,3];
(function(){for (var i = 0, max = list.length ; i < max ; i++ ){
  console.log(list[i]);
}}());
console.log(i); // i is not available outside the for block
<< 1
<< 2
<< 3
<< Error: "i is not defined"

Initialization Code

An IIFE can be used to set up any initialization code that there’ll be no need for again. Because the code is only run once, there’s no need to create any reusable, named functions, and all the variables will also be temporary. An IIFE will be invoked once and can set up any variables, objects, and event handlers when the page loads. The following example logs a welcome message to the console and then eliminates all the temporary variables that are used in putting the message together:

(function() {
  var name = "Bart"; // This might be obtained from a cookie in 
➥reality
  var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday",
➥"Friday","Saturday"];
  date = new Date();
  today = days[date.getDay()];
  console.log("Welcome back " + name + ". Today is " + today);

})();
<< "Welcome back Bart. Today is Sunday"

Safe Use of Strict Mode

In the last chapter we discussed using strict mode to avoid any sloppy coding practices. One of the problems with simply placing "use strict" at the beginning of a file is that it will enforce strict mode on all the JavaScript in the file, and if you’re using other people’s code, there’s no guarantee that they’ve coded in strict mode.

To avoid this, the recommended way to use strict mode is to place all your code inside an IIFE, like so:

(function() {
  "use strict";

  // All your code would go inside this function

   }());

This ensures that only your code inside the IIFE is forced to use strict mode.

Creating Self-contained Modules

An IIFE can be used to enclose a block of code inside its own private scope. This effectively creates a self-contained module that will not interfere with any other part of the program. Using IIFEs in this way means that code can be added or removed in a modular fashion. The example shows two modules, A and B, that are able to run code independently of each other:

(function() {
// Module A
  var name = "Module A";
  console.log("Hello from " + name);
}());

(function() {
// Module B
  var name = "Module B";
  console.log("Hello from " + name);
}());

<<  "Hello from Module A"
    "Hello from Module B

Notice that both modules include a variable called name, but the modules don’t interfere with each other. This is a useful approach for separating parts of a program into discrete modules, especially for testing purposes.

Get instant access to all books and courses.

Free Trial