Immediately Invoked Function Expressions
Learn the IIFE pattern that runs immediately and when to use it.
IIFE
An IIFE (Immediately Invoked Function Expression) is a function expression that runs as soon as it is defined. The pattern is (function() { ... })();. The outer parentheses turn the function into an expression, the trailing () invokes it right away.
Every variable declared inside the IIFE stays in its scope. Nothing leaks outside. This lets you do a one-off task without polluting the global scope.
Module isolation
The real power of an IIFE is isolation. Nothing you declare inside with let or const is visible from outside. The rest of the code cannot see the IIFE's internals; trying to reach them directly throws a reference error.
This property is the foundation of the module pattern you will see in the next lesson: you can expose only the methods you choose while keeping the state private. This reduces both clutter and side effects.
Exercise Write your first IIFE
Write an IIFE. Inside it, declare a private counter with let counter = 0, increment it with counter++ and log the result with console.log(counter). Use the (function() { ... })(); form.
Show example solution
(function() {
let counter = 0;
counter++;
console.log(counter);
})();
Test yourself
-
Complete the IIFE invocation
(function() { console.log("Running"); })____Show answer
(function() { console.log("Running"); })(); -
What is the main benefit of an IIFE?
- It runs the code faster
- It uses less memory
- It keeps variables out of the global scope
- It auto-names functions
Show answer
It keeps variables out of the global scope — Correct. An IIFE creates its own scope; variables inside do not pollute the global scope.
-
Match the IIFE terms
- IIFE
- Runs as soon as it is defined
- module isolation
- Keeping variables out of global scope
- immediately invoked
- Called right after definition