JS IIFEs
(function() {
// runs immediately
})();
(() => {
// runs immediately
})();
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.
उदाहरण: What Is an IIFE?
(function () {
// Print "Runs immediately" to the console
// Print "Runs immediately" to the console
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.
उदाहरण: 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.
उदाहरण: IIFE With Return
const result = (function () {
// Declare the constant `a`, set to `5, b = 10`
// Declare the constant `a`, set to `5, b = 10`
const a = 5, b = 10;
// Return `a + b` from this function
// Return `a + b` from this function
return a + b;
})();
// Print `result` to the console
// Print `result` to the console
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.
उदाहरण: IIFE With Parameters
(function (name) {
// Print `name` to the console
// Print `name` to the console
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.
उदाहरण: Modern Use
const config = (function () {
// Declare the constant `secret`, set to "key123"
// Declare the constant `secret`, set to "key123"
const secret = "key123";
// Return `{ getKey: () => secret }` from this function
// Return `{ getKey: () => secret }` from this function
return { getKey: () => secret };
})();
// Print `config.getKey()` to the console
// Print `config.getKey()` to the console
console.log(config.getKey());
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: