What is an IIFE and when would you use one?
Quick answer
An Immediately Invoked Function Expression runs the moment it's defined, creating a private scope.
In detail
Before ES modules, IIFEs were the main way to avoid polluting the global namespace and to create private state. Wrapping code in `(function(){ ... })()` gives it its own scope. Today modules cover most of this, but IIFEs still appear in bundlers and one-off initialisation.
const api = (function () {
let secret = 0; // private
return { bump: () => ++secret };
})();
api.bump(); // 1 — secret is inaccessible outsideWhy interviewers ask this: Tests understanding of scope isolation and history.
This is 1 of 118+ questions in the JavaScript Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the JavaScript Interview Kit → ₹299