IIFEs
Overview
An Immediately Invoked Function Expression (IIFE - pronounced 'iffy') is a JavaScript function that runs as soon as it is defined.
Historically, before let and const existed, var leaked out of blocks. IIFEs were the only way to create private scope and prevent variables from polluting the global window object. Today, they are mostly a legacy concept, though they are still used in older React setups or for top-level await.
Syntax
(function () {
const secretCode = "1234";
console.log("This runs immediately on page load!");
})();
// secretCode is completely inaccessible here
// console.log(secretCode); // ReferenceError// Used when top-level await is not supported
(async () => {
const data = await fetch('/api/config');
console.log("Config loaded");
})();Common Pitfalls
- Forgetting the terminating semicolon on the line BEFORE the IIFE. If the previous line doesn't have a semicolon, the JS engine might think you are trying to call the previous line's output as a function, causing a catastrophic
TypeError.
Interview Questions
Because var only respected function scope, not block scope. The only way to keep variables completely private and avoid global namespace collisions in large files was to wrap the code inside an anonymously invoked function (IIFE).
Real-World Example
Executing asynchronous setup logic at the very root of an application where top-level await is not permitted.
(async function init() {
await connectDatabase();
startServer();
})();Check Your Knowledge
Test your understanding of IIFEs with these quick questions.