IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.

Examples

The function becomes a function expression which is immediately executed. The variable within the expression can not be accessed from outside.

(function () { 
    var name = "Barry";
})();
// Variable name is not accessible from the outside scope
name // undefined

Assigning the IIFE to a variable does not store it but its result.

var result = (function () { 
    var name = "Barry"; 
    return name; 
})(); 
// Immediately creates the output: 
result; // "Barry"

Learn more

Learn about it

  • Quick example (at the end of the "Functions" section, right before "Custom objects")

General knowledge

Document Tags and Contributors

 Contributors to this page: vssn, tapa8728, bIgBV, rolfedh, lpiot, klez, Andrew_Pfeiffer
 Last updated by: vssn,