Profile Photo

Immediately Invoked Function Expression | working and usage

Created on: Aug 14, 2024

IIFE(Immediately Invoked Function Expression) is a function in JavaScript which immediately invoked and executed as soon as it is defined.

(function () { console.log("This function runs in IIFE!"); })();

Below are main features of IIFE.

  1. Private Scope Variables declared within the IIFE cannot be accessed by the outside world
  2. Avoiding Global Namespace Pollution. Try running below in browser console.
(function () { var counter = 0; function increment() { counter++; } increment(); console.log(counter); // 1 })(); console.log(x); // ReferenceError: x is not defined
  1. IIFE accepts parameter allowing you to pass in values and create variations of the function behavior without relying on external variables.
(function (a, b) { console.log(a + b); })(5, 10);

Real world usage in library or framework.

  1. The entire library in jQuery, Underscore.js, D3.js , Bootstrap (before version 5), is wrapped in an IIFE to ensure that all the internal variables and functions do not leak into the global scope.
  2. AngularJS, the original version of Angular, uses IIFE to define its modules and components. By doing so, it prevents variable name conflicts and keeps the code modular and isolated.