docs.rodeo

MDN Web Docs mirror

IIFE

{{GlossarySidebar}} 

An IIFE (Immediately Invoked Function Expression) is an idiom in which a {{glossary("JavaScript")}}  {{glossary("function")}}  runs as soon as it is defined. It is also known as a self-executing anonymous function. The name IIFE is promoted by Ben Alman in his blog.

// standard IIFE
(function () {
  // statements…
})();

// arrow function variant
(() => {
  // statements…
})();

// async IIFE
(async () => {
  // statements…
})();

It contains two major parts:

  1. A function expression. This usually needs to be enclosed in parentheses in order to be parsed correctly.
  2. Immediately calling the function expression. Arguments may be provided, though IIFEs without arguments are more common.

IIFEs are a common pattern used to execute arbitrarily many statements in their own scope (and possibly return a value), in a location that requires a single expression. They are similar to, but much more powerful than, the comma operator, which can only execute multiple expressions and, therefore, does not provide a way to use local variables or control flow statements.

Use cases of IIFEs include:

For code examples, see the function expression and async function expression reference pages.

See also

In this article

View on MDN