JavaScript Reference ยท Function
Immediately invoked function expressions (IIFE)
Reference for the JavaScript IIFE pattern: run a function expression immediately, create private scope, module pattern, async IIFEs and modern alternatives.
An immediately invoked function expression (IIFE, pronounced "iffy") is a function that is defined and called in the same step. The function creates its own scope, runs once, and its local variables disappear afterwards.
Before block-scoped let and ES modules existed, IIFEs were the standard way to avoid polluting the global scope. They are less common now, but still useful for one-off initialization and for running await in places where top-level await is not available.
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
How it works
A statement that starts with the keyword function is parsed as a function declaration, which needs a name and cannot be called directly. Wrapping the function in parentheses turns it into an expression, and the extra () calls it.
(function () { /* ... */ })(); // call outside the parentheses (function () { /* ... */ }()); // call inside the parentheses (() => { /* ... */ })(); // arrow function IIFE (async () => { /* ... */ })(); // async IIFE
Other unary operators such as !function () {}() or void function () {}() also work, but parentheses are clearer. If the previous line has no semicolon, a leading ( can be read as a call of the previous expression, so many style guides put a ; before an IIFE.
Usage notes
- Private variables: everything declared inside is invisible outside, which gives you the module pattern: return only the public API.
- Return value: the IIFE evaluates to whatever the function returns, so you can initialize a
constwith a computed value that needs several statements. - Block scope is often enough: a plain
{ ... }block withletandconstreplaces many IIFEs. - ES modules have their own scope per file, so they replace the module pattern.
- Async IIFE: an
asyncarrow returns a promise, so always handle its errors withtry/catchor.catch(), otherwise failures become unhandled rejections. thisinside a regular IIFE isundefinedin strict mode and the global object in sloppy mode; an arrow IIFE keeps the outerthis.- Named IIFEs (
(function init() {})()) give clearer stack traces, and the name is visible only inside the function. - Directives: code inside an IIFE can start with its own
"use strict"directive without making the whole file strict.
Browser support
IIFEs use only core syntax and work in every JavaScript engine. Async and arrow IIFEs need a modern environment.
Related
- Closures, hoisting
async function,use strict- Lessons: Functions, Scope, Modules