IIFE Explained with Examples - Private Scope in JS
What is IIFE?
- IIFE stands for Immediately Invoked Function Expression
- It is a function that executes immediately after being defined
- No need to call it manually
Basic Syntax
(function(){
// code
})();
(() => {
// code
})();
- Function is wrapped inside
() - Then immediately invoked using
()
Why Use IIFE?
Main purposes:
- Create private scope
- Avoid global variable pollution
Problem Without IIFE
let fruitName = "banana";
console.log(fruitName);
Issue:
fruitNamebecomes part of the global scope (window object)
Solution Using IIFE
(function(){
let fruitName = "banana";
console.log(fruitName);
})();
Now:
fruitNameis private- Not accessible globally
IIFE vs Normal Function
Normal Function
function fruit(){
let name = "banana";
console.log(name);
}
fruit();
- Requires manual call
IIFE
(function(){
let name = "banana";
console.log(name);
})();
- 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");
- 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:
countis private- Cannot be accessed outside the IIFE
Key Concepts
- IIFE creates a private scope
- Variables inside IIFE are not global
- Used for data protection
- Executes immediately
Where to Use IIFE
- Avoid global variable conflicts
- Data hiding (private variables)
- One-time execution logic
- Module pattern