What is an IIFE in JavaScript

· Category: JavaScript

Short answer

An IIFE is a function expression that is defined and executed immediately, creating a private scope to avoid polluting the global namespace.

How it works

Wrapping a function in parentheses turns it into an expression. Appending () invokes it right away. Variables declared inside are not accessible from the outside.

Example

(function() {
  const secret = 42;
  console.log(secret);
})();
// console.log(secret); // ReferenceError

// With parameters
((name) => {
  console.log(`Hello, ${name}`);
})('World');

Why it matters

IIFEs were the primary module pattern before ES6 modules. They protect variables from global scope collisions and enable private state without classes. Modern code often prefers modules or block-scoped let/const, but IIFEs remain useful in scripts without module systems.