An IIFE (Immediately Invoked Function Expression) is a JavaScript function that is defined and executed immediately after its creation.
It looks like this:
(function () {
console.log("This is an IIFE!");
})();
🔹 Breakdown:
- Function Expression
(function() { ... })→ The function is wrapped inside parentheses so that JavaScript treats it as an expression (not a declaration).
- Immediate Invocation
()right after the function tells the engine to execute it immediately.
🔹 Why use IIFE?
Avoid polluting the global scope
Variables inside an IIFE are private and cannot be accessed outside.
(function () {
var privateVar = "I am private";
console.log(privateVar); // ✅ Accessible here
})();
// console.log(privateVar); // ❌ Error: privateVar is not definedCreate private scope (especially useful before let and const were introduced in ES6).
Run code immediately without explicitly calling a function later.
🔹 Variations
Named IIFE (function myFunc() { console.log("Named IIFE"); })();
Arrow Function IIFE (() => { console.log("IIFE with arrow function"); })();
With Parameters ((name) => { console.log("Hello " + name); })("Himanshu");✅ In short:
An IIFE is a function expression that executes immediately after being created, mainly used for data privacy and avoiding global namespace pollution.
