Immediately Invoked Function Expressions
An immediately invoked function expression, or IIFE, is a function that runs as soon as it is defined. It is written as a function expression wrapped in parentheses, followed by a second pair of parentheses that calls it.
(function () { const greeting = 'Good morning'; console.log(`${greeting}, the shop is open`);})();
console.log(typeof greeting);This prints:
Good morning, the shop is openundefinedThe first pair of parentheses matters because a line that starts with the word function is read as a function declaration, and a declaration cannot be called on the spot. The parentheses turn it into an expression, which can. The variables declared inside belong to the function, so greeting does not exist outside it.
Keeping state private
Section titled “Keeping state private”The main use of an IIFE is to create a private scope and hand back only what the rest of the program needs. Here the items array can be reached only through the two methods that the IIFE returns:
const basket = (() => { const items = [];
return { add(name, price) { items.push({ name, price }); }, total() { return items.reduce((sum, item) => sum + item.price, 0); }, };})();
basket.add('Bread', 1.45);basket.add('Milk', 0.95);console.log(basket.total());console.log(basket.items);This prints:
2.4undefinedThe returned methods keep access to items after the IIFE has finished, because they are closures over its scope. Older code used this pattern to build modules, and Namespaces and IIFEs vs Namespaces look at it further. An arrow function works as an IIFE too, as long as it is wrapped in parentheses.
Computing a value once
Section titled “Computing a value once”An IIFE can take arguments and return a value, which suits a constant that needs a few statements to work out:
const taxRate = ((region) => { if (region === 'UK') return 0.2; if (region === 'IE') return 0.23; return 0;})('UK');
console.log(taxRate);This prints:
0.2Async IIFEs
Section titled “Async IIFEs”Before top-level await existed, an async IIFE was the usual way to use await in a script. It is still needed in a classic script or a CommonJS file, where top-level await is not allowed:
(async () => { const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); console.log('Loading settings'); await wait(100); console.log('Settings loaded');})();
console.log('Carrying on');This prints:
Loading settingsCarrying onSettings loadedThe IIFE returns a promise when it reaches its first await, so the line after the IIFE runs before the rest of the function does.
Pitfalls
Section titled “Pitfalls”When the line before an IIFE has no semicolon, JavaScript reads the opening parenthesis as a call on whatever came before it:
const shopName = 'Corner Stores'(function () { console.log('Starting up');})();This throws TypeError: "Corner Stores" is not a function. Code written without semicolons often starts an IIFE with ;( for this reason.
IIFEs are less common than they were, because let and const already give every block its own scope, and an ES module keeps its top-level variables private. They are still useful for a one-off async block and for working out a constant in place.
Steve Griffith covers this topic in his video JavaScript IIFE (Immediately Invoked Function Expressions).