CodePark/ questions / Scope & hoisting
START PRACTICINGPRACTICE
Frontend question · JavaScript › Scope & hoisting

What is an IIFE and why was it used?

const counter = (() => {
  let count = 0;
  return { inc: () => ++count };
})();

An IIFE (Immediately Invoked Function Expression) is a function that runs right where it is defined. Examples are (function () { ... })() and (() => { ... })().

The extra parentheses around the function matter. They make the parser read it as an expression, not as a function declaration, so it can be called at once.

Before let, const and ES modules, an IIFE was the main way to create a private scope. Variables inside it did not leak into the global scope. This stopped different scripts on the same page from overwriting each other's names.

It was also the base of the module pattern. The IIFE returns an object with only the public functions. Closures keep everything else private. In the example above, count is private and only inc is public.

Today, block scope and modules do most of this job. You still see IIFEs in bundler output. People also use them to run async code at the top level in places where top-level await is not available.

  • An IIFE is a function expression that is called immediately.
  • It creates a private scope, so its variables do not become globals.
  • It was the base of the classic module pattern, using closures to keep data private.
  • Block scope and ES modules have mostly replaced it.