Problem Statement
What is an IIFE (Immediately Invoked Function Expression)?
Explanation
An IIFE is a function that runs immediately after it is defined. It is wrapped in parentheses and followed by another set of parentheses to invoke it.
IIFEs create a new scope, preventing variables from polluting the global scope.
They were commonly used before ES6 modules for encapsulation.
IIFEs can return values or objects.
The pattern is useful for initialization code that runs once.
Modern JavaScript uses modules instead, but IIFEs still appear in legacy code and are good interview questions.
Code Solution
SolutionRead Only
// Basic IIFE syntax
(function() {
console.log('I run immediately!');
})();
// Arrow function IIFE
(() => {
console.log('Arrow IIFE');
})();
// IIFE with parameters
(function(name) {
console.log('Hello ' + name);
})('John');
// IIFE returning a value
const result = (function() {
return 2 + 2;
})();
console.log(result); // 4
// Creating private variables
const counter = (function() {
let count = 0; // Private variable
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
})();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
// console.log(counter.count); // undefined (private!)
// Module pattern with IIFE
const myModule = (function() {
// Private
const privateVar = 'I am private';
function privateFunction() {
console.log(privateVar);
}
// Public API
return {
publicMethod: function() {
privateFunction();
},
publicVar: 'I am public'
};
})();
myModule.publicMethod(); // 'I am private'
console.log(myModule.publicVar); // 'I am public'
// console.log(myModule.privateVar); // undefined
// Avoid global pollution
(function() {
var temp = 'Only exists in this scope';
// Do something
})();
// console.log(temp); // ReferenceError
// Classic var loop fix
for (var i = 0; i < 3; i++) {
(function(index) {
setTimeout(function() {
console.log(index); // 0, 1, 2
}, 100);
})(i);
}