Home Courses IIFE Explained with Examples - Private Scope in JS

IIFE Explained with Examples - Private Scope in JS

What is IIFE?

  1. IIFE stands for Immediately Invoked Function Expression
  2. It is a function that executes immediately after being defined
  3. No need to call it manually


Basic Syntax


(function(){
// code
})();

(() => {
// code
})();

  1. Function is wrapped inside ()
  2. Then immediately invoked using ()


Why Use IIFE?

Main purposes:

  1. Create private scope
  2. Avoid global variable pollution


Problem Without IIFE


let fruitName = "banana";
console.log(fruitName);

Issue:

  1. fruitName becomes part of the global scope (window object)


Solution Using IIFE


(function(){
let fruitName = "banana";
console.log(fruitName);
})();

Now:

  1. fruitName is private
  2. Not accessible globally


IIFE vs Normal Function

Normal Function


function fruit(){
let name = "banana";
console.log(name);
}
fruit();

  1. Requires manual call


IIFE


(function(){
let name = "banana";
console.log(name);
})();

  1. Executes automatically


Passing Parameters in IIFE


(function(color){
console.log(color);
})("green");

Output: green


Arrow Function IIFE


((color) => {
let fruit = "banana";
console.log(fruit, color);
})("red");

  1. Works the same as normal IIFE


Returning Value from IIFE


const result = (() => {
return 2 + 2;
})();

console.log(result);

Output: 4


Creating Private Variables


const counter = (() => {
var count = 0;

return {
increment: function(){
count++;
console.log(count);
},
decrement: function(){
count--;
console.log(count);
}
};
})();


Using the Counter


counter.increment(); // 1
counter.increment(); // 2
counter.increment(); // 3


Private Property Concept


console.log(counter.count);

Output: undefined

Reason:

  1. count is private
  2. Cannot be accessed outside the IIFE


Key Concepts

  1. IIFE creates a private scope
  2. Variables inside IIFE are not global
  3. Used for data protection
  4. Executes immediately


Where to Use IIFE

  1. Avoid global variable conflicts
  2. Data hiding (private variables)
  3. One-time execution logic
  4. Module pattern


Share this lesson: