JS IIFEs
What Is an IIFE?
IIFE means Immediately Invoked Function Expression. It runs as soon as it is created. Wrapping code in (function(){ ... })() executes it once immediately without leaving a named function sitting around afterward.
Example: What Is an IIFE?
(function () {
console.log("Runs immediately");
})();
Why Use IIFEs?
An IIFE creates its own scope. Variables inside it do not become global variables. Before ES modules were standard, this was the primary way libraries avoided polluting the global namespace with their internal helper variables.
Example: Why Use IIFEs?
(function () {
var secret = "hidden"; // not a global variable
console.log(secret);
})();
console.log(typeof secret); // "undefined"
IIFE With Return
An IIFE can return a value immediately. Store that returned value in a variable. This pattern, const result = (function(){ ... return value; })(), lets you compute a value using local helper variables that don't leak outside the IIFE.
Example: IIFE With Return
const result = (function () {
const a = 5, b = 10;
return a + b;
})();
console.log(result);
IIFE With Parameters
An IIFE can accept arguments just like a normal function. For example, (function(name){ console.log(name); })(Alice) behaves like calling a regular function, just invoked exactly once at definition time.
Example: IIFE With Parameters
(function (name) {
console.log(name);
})("Alice");
Modern Use
Modules are more common today, but IIFEs are still useful when you need an isolated scope in a script. Even in module-based codebases, a small IIFE is still occasionally reached for when you need a self-contained block of setup logic that shouldn't expose its internals.
Example: Modern Use
const config = (function () {
const secret = "key123";
return { getKey: () => secret };
})();
console.log(config.getKey());
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: