What is IIFE (immediately invoked Function expression) in JavaScript
IIFE (Immediately Invoked Function Expression) is an immediately invoked function expression in JavaScript. It's a function that is defined and immediately called as soon as the interpreter reaches it.
Syntax
javascript
(function () {
// code inside IIFE
})();Or using arrow function:
javascript
(() => {
// code inside IIFE
})();Why Use IIFE?
- Isolates variables and functions from outer scope.
- Used to create local scope, especially before let and const appeared.
- Often used in modular development when you need to hide internal implementation details.
Usage Example
javascript
(function () {
const message = "Hello from IIFE!";
console.log(message); // "Hello from IIFE!"
})();
console.log(message); // ReferenceError: message is not definedVariable message is only available inside IIFE and inaccessible outside — this avoids polluting global scope.
IIFE with Arguments
javascript
(function (name) {
console.log(`Hello, ${name}!`);
})("Alice"); // Hello, Alice!When is it Used?
- For one-time data initialization (e.g., setup)
- For creating private variables and closures
- In old pre-ES6 projects for module simulation
Example: counter with closure via IIFE
javascript
const counter = (function () {
let count = 0;
return function () {
count++;
console.log(count);
};
})();
counter(); // 1
counter(); // 2Summary
IIFE is a function that is immediately called after definition.
- Used for code isolation and creating private namespace.
- It's a useful technique for writing modular and safe code.
Fact:
IIFE is one of the simplest ways to organize privacy in JavaScript without classes and modules.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.