What is an IIFE?

An IIFE (Immediately Invoked Function Expression) is a function that is defined and called in the same expression, (function () { ... })(), used to run code once inside its own private scope.

Why it existed

Before ES modules and block scope, every top-level var in a script became a global. Wrapping code in an IIFE kept variables private and prevented collisions between scripts. It was the basis of the module pattern and of libraries like jQuery plugins.

Syntax

The parentheses around the function turn it into an expression so it can be called immediately:

  • (function () { ... })();
  • (() => { ... })();
  • (async () => { ... })(); for running await where top-level await is not available.

Starting a line with ( after a line without a semicolon can merge the two lines, which is why older code often starts IIFEs with ;(function....

Is it still useful today?

Much less, because ES modules give every file its own scope and let/const give block scope. It still appears for:

  • Running async code in environments without top-level await (older Node scripts, some build tools).
  • Creating a private scope inside a classic <script> tag or a bookmarklet.
  • Computing a const value with several steps: const config = (() => { ... return result; })();
  • Bundler output, which still wraps modules in function scopes.

Code example

js
1// Private state with an IIFE (the classic module pattern)
2const counter = (function () {
3 let count = 0; // not reachable from outside
4 return {
5 increment: () => ++count,
6 get value() {
7 return count;
8 },
9 };
10})();
11counter.increment();
12counter.increment();
13console.log(counter.value, typeof count); // 2 "undefined"
14
15// Computing a const in several steps
16const config = (() => {
17 const env = "production";
18 const base = { retries: 3, debug: false };
19 return env === "production" ? base : { ...base, debug: true };
20})();
21console.log(config); // { retries: 3, debug: false }
22
23// Async IIFE: run await where top-level await isn't available
24(async () => {
25 const data = await new Promise((resolve) => setTimeout(() => resolve("loaded"), 10));
26 console.log("async IIFE:", data); // async IIFE: loaded
27})();
28
29await new Promise((r) => setTimeout(r, 30));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app