IIFE
A self-invoking function (IIFE - Immediately Invoked Function Expression) is a function that is created and invoked right away, without a separate call by name.
Syntax:
(function () {
console.log('I ran right after being declared!');
})();Notice the two pairs of parentheses:
- The first
(function() { ... })- turns the function into a function expression. - The second
()- immediately invokes that function.
Example with parameters:
(function (name) {
console.log(`Hello, ${name}!`);
})('Tim');Prints:
Hello, Tim!What IIFE is used for
1. Creating an isolated scope
IIFE is often used to avoid variable conflicts - for example, when writing code that should not "pollute" the global scope (window or global).
(function() {
const secret = 'Secret inside the function';
console.log(secret);
})();
console.log(secret); // ReferenceError: secret is not definedThe secret variable is only accessible inside the IIFE.
2. One-time code initialization
You can use an IIFE to run something once, on load:
const config = (() => {
const apiKey = '12345';
const baseUrl = 'https://api.example.com';
return { apiKey, baseUrl };
})();
console.log(config.apiKey); // 12345We return an object, but the variables inside stay encapsulated.
3. Use with async / await
An IIFE can be made asynchronous to use await at the top level:
(async () => {
const data = await fetch('/api/data').then(res => res.json());
console.log(data);
})();Historically
Before ES6 modules appeared (where every import/export file unit now has its own scope),
IIFEs were actively used in JavaScript for encapsulation and code structuring.
They are used less often now, but are still useful for:
- one-time initialization,
- isolating temporary variables,
- immediately running async code.
In short:
| Trait | Description |
|---|---|
| Name | IIFE - Immediately Invoked Function Expression |
| Essence | The function is created and invoked right away |
| Why | Isolation, initialization, temporary variables |
| Traits | Does not pollute the global scope, can be async |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.