JavaScript Immediately Invoked Functions
An immediately invoked function runs at once, in the same breath as its definition. The shape wraps a function in parentheses and calls it right away.
A function that runs at once
The parentheses hold the function, and the trailing pair calls it. No name and no later call are needed.
(function () {
console.log("Runs at once");
})();An arrow IIFE
An arrow function works the same way. The shape is shorter, and it still runs at once.
(() => {
console.log("Also at once");
})();It once guarded scope
The IIFE declares its own count with var. The outer count stays 1, so the guard keeps the two apart.
var count = 1;
(function () {
var count = 2;
console.log(count);
})();
console.log(count);Example
var label = "outside";
(function (label) {
console.log("Inside: " + label);
})("inside");
console.log("Outside: " + label);Key points
- Immediately invoked function expression: a function that runs as soon as it is defined
- The short name for the shape is IIFE.
- Parentheses around the function turn it into an expression.
- The trailing parentheses call the function at once.
- An IIFE can take arguments, like any function call.
- Before block scope, an IIFE guarded variables from the outside world.
In this example, the IIFE takes a label argument and logs it inside. The inner label is inside, and the outer label stays outside. The argument passes a value in without touching the outer variable.
Note
Modern code uses blocks and modules for scope, so the IIFE guard is now a historical pattern.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does an IIFE do?