← all writing

IIFE in JavaScript

IIFE means "Immediately Invoked Function Expression". It is a powerful JavaScript feature used to create self-contained and private scopes. It is essentially an anonymous function that is wrapped within a set of parentheses and immediately executed. We use IIFE to place all our code inside of a local scope or to avoid global scope.

Basic Syntax

(function () {
  // our code goes here
})();

The above code demonstrates the basic syntax of an IIFE. The function is declared and invoked in one go, and it acts as a standalone block of code.

Local Scope and Avoiding Global Scope

One of the primary reasons for using IIFE is to avoid polluting the global scope with variables and functions. When you define variables inside an IIFE, they are confined to its local scope, preventing any conflicts with other parts of your code.

Example

var name = 'deepak';
 
(function () {
  var city = 'Bhopal';
  console.log(city);   // -> 'Bhopal'
})();
 
console.log(name);     // -> 'deepak'
console.log(city);     // -> ReferenceError: city is not defined

In this example, the variable name can be accessed both inside and outside the IIFE since it was declared globally. However, the variable city is only accessible within the IIFE's local scope, and attempting to access it from outside results in a ReferenceError.

Encapsulation and Private Variables

IIFE provides a way to encapsulate your code, making it easier to manage and reducing the risk of conflicts with other scripts. You can create private variables within the IIFE that are not accessible from the outside, achieving data privacy.

Example

var counter = (function () {
  var count = 0;
 
  return {
    increment: function () {
      count++;
    },
    getCount: function () {
      return count;
    }
  };
})();
 
counter.increment();
console.log(counter.getCount());   // Output: 1
console.log(count);                // Output: ReferenceError: count is not defined

In this example, the IIFE acts as a module that keeps the count variable private, allowing only the increment and getCount methods to access and modify its value.

Modern Alternatives

While IIFE is a powerful technique, modern JavaScript offers other ways to achieve encapsulation and avoid global scope using modules (e.g., ES6 modules). When working with modern JavaScript, consider exploring these alternatives as well.