Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Immediately invoked function expression (IIFE) syntax

An IIFE creates and calls a function in one expression. Grouping parentheses do not call the function; the argument list that follows them does.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

(function (parameter) { /* body */ })(argument);
(function localName(parameter) { /* body */ })(argument);

The IIFE function expression syntax combines grouping and a call: in (function (parameter) { /* body */ })(argument), the parentheses around function … { … } group the function expression, and the trailing (argument) calls the resulting function. Use () to pass no arguments. Grouping alone does not run the body. The call happens each time the expression is evaluated.

An expression statement cannot start with function. Without grouping, function () {}(); in that position causes a SyntaxError because the anonymous form is not a valid declaration there. A function expression can be anonymous or named; localName in the named form does not create a binding in the surrounding scope.

Local declarations in the body do not become accessible by name in the surrounding code. A returned closure can still access them after the call ends. A value passed to return becomes the result of the call; if an ordinary function reaches the end without a return, the result is undefined.

If a standalone IIFE starts a line with (, end the preceding statement with a semicolon or start the IIFE with ;(. A line break alone does not guarantee separation: the parser can treat ( as the start of an argument list that calls the preceding expression.

Examples

const total = (function (price) {
  const fee = 2;
  return price + fee;
})(40);

console.log(total);

Result

42

The argument `40` is passed to `price`. The variable `fee` stays local, and `total` receives the returned value `42`, not the function.

Related lessons

  • JavaScript · Lesson 30 · Advanced · Version: 4

Sources