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
(function () {
// code inside IIFE
})();
Or using arrow function:
(() => {
// 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
(function () {
const message = "Hello from IIFE!";
console.log(message); // "Hello from IIFE!"
})();
console.log(message); // ReferenceError: message is not defined
Variable message is only available inside IIFE and inaccessible outside — this avoids polluting global scope.
IIFE with Arguments
(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
const counter = (function () {
let count = 0;
return function () {
count++;
console.log(count);
};
})();
counter(); // 1
counter(); // 2
Summary
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.