JavaScript Basic
What is an IIFE (Immediately Invoked Function Expression) in JavaScript? What are the pros and cons?
What is an IIFE?
An IIFE (Immediately Invoked Function Expression) is a function that is defined and executed immediately.
// Basic syntax
(function() {
// function body
})();
// Arrow function version
(() => {
// function body
})();
// With parameters
(function(name) {
console.log('Hello, ' + name);
})('World');
Why the Wrapping Parentheses?
The function must be wrapped in parentheses so the JavaScript parser treats it as an expression rather than a declaration. Without them, a leading function keyword is parsed as a function declaration, which cannot be immediately invoked.
Advantages
1. Avoids Polluting the Global Scope
(function() {
var secret = '123'; // only exists inside the IIFE
})();
console.log(typeof secret); // 'undefined'
2. Creates a Private Scope
Simulates module encapsulation for variables and logic.
3. Prevents Variable Conflicts
Especially useful in legacy environments where multiple scripts coexist.
4. Runs Initialization Logic
Great for one-time setup code that runs immediately.
Disadvantages
- Reduced readability: The syntax is obscure and not intuitive
- Hard to test: Logic inside an IIFE is difficult to unit test
- Modern alternatives exist: ES6
let/consthave block scope, and ES modules (ESM) provide better encapsulation, greatly reducing the need for IIFEs
Modern Alternatives
// ES Modules (recommended)
// Variables in a module are private by default
// Block scope
{
let secret = '123';
}
console.log(typeof secret); // 'undefined'
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
