What is an IIFE in JavaScript?
BeginnerJavaScript interview questionBy UIRound, updated 17 November 2026
Short answer
An IIFE (immediately invoked function expression) is a function that is defined and called in the same expression, such as (function () { ... })(). It runs once, straight away, and gives the code inside its own scope. Before let, const and ES modules, that was the only way to keep variables private instead of leaking them into the global scope.
The syntax
(function () {
const secret = 42;
console.log("runs immediately", secret);
})();
console.log(typeof secret); // "undefined": the variable stayed insideThere are two parts. The parentheses around the function turn it into an expression, and the () after it calls it. Arguments go in the second pair: (function (name) { ... })("Asha").
The wrapping parentheses are needed because a line that starts with the function keyword is parsed as a function declaration, not an expression. A declaration cannot be called on the spot:
function () {}(); // SyntaxError: function statements require a name
function run() {}(); // SyntaxError: the trailing () is an empty group
function run() {}(1); // No error, but nothing is called: a declaration, then the expression (1)The last line is a classic trick question. It looks like a call, but it declares run and then evaluates (1) on its own. The function declaration vs function expression answer explains why the parser treats these differently.
Variants you will see
(function () { /* ... */ })(); // the common form
(function () { /* ... */ }()); // call inside the parentheses, same result
(() => { /* ... */ })(); // arrow IIFE: the arrow must be wrapped
!function () { /* ... */ }(); // a unary operator also forces an expression
void function () { /* ... */ }(); // same, and makes it clear the result is ignoredWith an arrow function, only the first style works. (() => {}()) is a syntax error because an arrow function cannot be called without its own parentheses.
You will also see a leading semicolon, ;(function () { ... })(). It protects against a previous line that has no semicolon. Without it, const a = b followed by an IIFE on the next line is read as b(function () { ... })(), which calls b.
Why IIFEs existed
Before ES2015, JavaScript had only function scope and global scope. A var at the top level of a classic script became a global, and every script on the page shared those globals. Two libraries that both declared var config would overwrite each other. Wrapping each file in an IIFE gave it a private scope, because the only way to create a new scope was to call a function.
That led to a few patterns that interviewers still ask about.
The module pattern. Return only what should be public, and keep the rest in the closure:
const counter = (function () {
let count = 0; // private
return {
increment() { return ++count; },
reset() { count = 0; },
};
})();
counter.increment(); // 1
counter.count; // undefinedThis works because of closures: the returned methods keep access to count after the IIFE has finished.
Fixing the var loop bug. All callbacks below shared one i. An IIFE created a new scope for each iteration:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 0); // 0, 1, 2
})(i);
}With let in the loop header, each iteration already gets its own binding, so this fix is no longer needed. See var, let and const.
Passing in globals. Libraries wrote (function ($, window) { ... })(jQuery, window) to use short local names and avoid clashes with other code that used $.
The async IIFE
await only works inside an async function or at the top level of an ES module. In a CommonJS Node script, a classic browser script or a callback that cannot itself be async, an async IIFE lets you use await:
(async () => {
try {
const res = await fetch("/api/user");
const user = await res.json();
console.log(user.name);
} catch (error) {
console.error("Failed to load user", error);
}
})();The IIFE returns a promise. Nothing awaits it, so handle errors inside it, or add .catch() to the call. Otherwise a failure becomes an unhandled rejection.
In an ES module (<script type="module">, .mjs, or a project with "type": "module"), top-level await works directly and the async IIFE is unnecessary.
Is it still useful?
Much less than it was. Block scope and modules solved the problem it was invented for:
| Need | Before ES2015 | Today |
|---|---|---|
| Keep a file's variables private | Wrap the file in an IIFE | ES modules have their own scope |
| A temporary scope inside a function | IIFE | A block { let x = ... } |
| A fresh variable per loop iteration | IIFE with a parameter | let in the loop header |
await at the top level |
Not possible | Top-level await in modules, or an async IIFE elsewhere |
It still has a few honest uses:
- Computing a
constwith several steps:const theme = (() => { ... return value; })();keeps the helper variables out of the outer scope. - An async IIFE in places that cannot be async, such as a script without modules.
- Bundler output. Tools such as Rollup and esbuild can emit an IIFE build so a library can be loaded with a plain
<script>tag without leaking globals.
Practise it
Predict 1 + function coercion and override toString with an IIFE uses an IIFE directly. Fix the var loop closure bug three ways includes the IIFE fix, Predict closure results tests the scope rules behind it, and Implement singleton, factory and strategy patterns is where the module pattern fits.
Common follow-up questions
Can an IIFE have a name?
Yes: (function init() { ... })(). The name is only visible inside the function, so it does not leak. It helps stack traces and lets the function call itself recursively.
What is this inside an IIFE?
this inside an IIFE?A regular function IIFE is called without a receiver, so this is undefined in strict mode and the global object in sloppy mode. An arrow IIFE uses the this of the surrounding code.
Is an IIFE the same as a closure?
No. An IIFE is a way of calling a function. A closure is a function keeping access to its outer variables. They often appear together, as in the module pattern, but one does not need the other.
Does an IIFE help performance?
Not in any way you should rely on. Choose it for scoping, not speed.
Mistakes to avoid
Writing
function () {}()without wrapping parentheses and getting a syntax errorStarting a line with an IIFE after a line with no semicolon, so the previous value is called
Forgetting to handle rejections in an async IIFE
Reaching for an IIFE where a block,
letor a module already gives you the scopeSaying an IIFE is needed for privacy in modern code
Modules and private class fields (
#count) cover that.
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Predict
1 + functioncoercion, and overridetoStringwith an IIFE and a closureEasy25 min - Fix the
varloop closure bug three waysEasy15 min - Predict closure results: counters, loops, captured variables and lexical scopeEasy20 min
- Implement singleton, factory and strategy patterns idiomatically in JavaScriptMedium40 min