Learnitweb

Immediately-invoked Function Expressions (IIFE) In JavaScript

1. Introduction

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. An IIFE looks like the following:

(function () {
  //executable statements
})();

Let us understand IIFE with the help of an example.

(function () {
  console.log("hello world");
})();

//output is: hello world

In the above code:

  1. there is no name of the function, it is an anonymous function.
  2. anonymous function is enclosed between ( and ) which is also known as grouping operator. Grouping operator is used to control the precedence of evaluation in expressions.
  3. there is () in the end which creates a immediately invoked function expression.

2. Benefits of using IIFE

  1. IIFE is an effective way to shield the expression from rest of the program.
  2. IIFEs keep any variables wrapped up within the scope of the function. This means the global namespace is not polluted with more variable names.
  3. IIFE also limits closure memory problem because there is no reference to the anonymous function.

ECMAScript 5.1 or before, IIFE was a very useful pattern to prevent global namespace pollution.

3. Using Arrow Functions to Create IIFEs

We already discussed how to create IIFE. For example:

var fn = (function (number) {
  return {
    getNumber: function () {
      return number;
    },
  };
})(15);
console.log(fn.getNumber()); // Output is: 15

We can also use arrow function to create IIFE. The above code could be written using arrow function as:

var fn = ((number) => {
  return {
    getNumber: function () {
      return number;
    },
  };
})(15);
console.log(fn.getNumber()); // Output is: 15

4. Named IIFE

You can provide a name to the function. This will not change anything to being a IIFE.

(function hello() {
  console.log("hello world");
})();

5. IIFE avoid polluting global namespace

If there is some code which we do not need reuse, for example initialization code in your program. We can use IIFE for this requirement. Variables declared inside the IIFE are discarded after the function is executed.

(function () {
  // variables declared here will be discarded after the function is executed
})();

6. Safe use of strict mode with IIFE

When you are using code which someone else has written, if you add use strict at the beginning of the file, it will make the entire file to follow the strict mode. You may not be sure that other people have also followed strict mode. To avoid this problem, you can place all your code in an IIFE and use strict mode in IIFE.

(function() {
'use strict';
// Add your code here.
})();

This will make only your code written in IIFE to follow strict mode.

7. Module pattern

Module pattern is used to encapsulate variables and methods and disclose only the required information. Using IIFE we can achieve the same. Before class was introduced, IIFE was used to create the same effect as of class to very the much extent.

Let us see how you can create a private variable and public method using IIFE. We’ll create a private variable and will then create two methods – one to set variable and another to get the value of variable.

const fn = (function () {
  let privateVariable = 5;

  return {
    setPrivateVariable: function (value) {
      privateVariable = value;
    },
    getPrivateVariable() {
      return privateVariable;
    },
  };
})();

fn.setPrivateVariable(7);
console.log(fn.getPrivateVariable()); //output is 7

In this example:

  • privateVariable can’t be accessed directly from outside the IIFE.
  • Function setPrivateVariable is the privileged method which has access to the privateVariable and can set the value.
  • Function getPrivateVariable is the privileged method and has access to the privateVariable and we have used it to return the value.

8. Conclusion

In this tutorial, we discussed about the Immediately Invoked Function Expression (IIFE) in JavaScript. Every JavaScript developer should know about IIFE. You may find this pattern in old as well as new JavaScript code. In this tutorial, we discussed how to write IIFE and use it to create modular pattern. Understanding this pattern will help you to understand and write modular code.