JavaScript Notes
Master closure interview questions with detailed answers, code examples, outputs, common traps, and tips. Covers IIFE, loop problem, data privacy, currying, memoization.
Closures are one of the most asked topics in JavaScript interviews. This page covers every pattern an interviewer can throw at you — from basic definition to tricky output prediction.
Tips for Interview 💡
- Always say: *"A closure gives a function access to its outer scope even after the outer function returns."*
- Mention lexical scope — not dynamic scope.
- Say closures are formed at function creation time, not invocation time.
- Mention real use cases: counter, memoization, debounce, module pattern.
Q1: Basic Closure — What is the output?
function makeGreeting(name) {
return function () {
console.log("Hello, " + name + "!");
};
}
const greetAlice = makeGreeting("Alice");
const greetBob = makeGreeting("Bob");
greetAlice();
greetBob();
greetAlice();Hello, Alice! Hello, Bob! Hello, Alice!
Explanation: Each call to makeGreeting creates a new closure with its own name binding. greetAlice and greetBob are completely independent closures.
Q2: Counter Closure — Implement a private counter
1 2 1 2 0
Explanation: c1 and c2 each have their own separate count variable. This is data encapsulation via closures — count is private and cannot be accessed or modified directly.
Q3: The Classic Loop Problem (var vs let)
Most asked tricky question in interviews!
4 4 4
Why? var is function-scoped. All three callbacks share the same i variable. By the time the timeouts fire, the loop has ended and i === 4.
Fix 1 — Use let (block scope per iteration):
1 2 3
Fix 2 — Use IIFE to capture value:
1 2 3
Common Traps 🪤
| Trap | Explanation |
|---|---|
var in loops | All callbacks share the same variable reference |
| Closure over object reference | Mutating the object affects all closures |
this inside closure | Arrow function vs regular function this |
| Memory leaks | Large objects captured and never released |
Q4: Separate Closures — Shared State?
1 2 1 3
Explanation: fn1 and fn2 are created by separate calls to outer(), so they each have their own independent count.
Q5: Lexical Scope — Not Dynamic Scope
let x = 10;
function foo() {
console.log(x);
}
function bar() {
let x = 99;
foo(); // foo uses x from WHERE IT WAS DEFINED, not where it's called
}
bar();10
Key Rule: JavaScript is lexically scoped. foo looks up x in the scope where foo was defined (global), NOT where it's called (inside bar).
Q6: Closure with Array — Output Question
3 3 3
Explanation: All three closures reference the same var i variable, which is 3 after the loop.
Fix using let:
0 1 2
Q7: What does a Closure "close over"?
function multiplier(factor) {
return function (number) {
return number * factor; // "closes over" factor
};
}
const double = multiplier(2);
const triple = multiplier(3);
const tenTimes = multiplier(10);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(tenTimes(5)); // 5010 15 50
Use Case: Function factories — create specialized functions from a generic one. Common in functional programming.
Q8: Closure for Data Privacy
function BankAccount(initialBalance) {
let balance = initialBalance; // PRIVATE
return {
deposit(amount) {
balance += amount;
console.log(`Deposited ₹${amount}. Balance: ₹${balance}`);
},
withdraw(amount) {
if (amount > balance) return console.log("Insufficient funds!");
balance -= amount;
console.log(`Withdrawn ₹${amount}. Balance: ₹${balance}`);
},
getBalance() {
return balance;
}
};
}
const acc = BankAccount(1000);
acc.deposit(500);
acc.withdraw(200);
console.log("Balance:", acc.getBalance());
console.log("Direct access:", acc.balance); // undefined!Deposited ₹500. Balance: ₹1500 Withdrawn ₹200. Balance: ₹1300 Balance: 1300 Direct access: undefined
Q9: Once Function — Run Only One Time
Initialized! 42 42 42
Q10: Memoize Function (Closure + Cache)
Computing... 25 Cache hit: [5] 25 Computing... 36
Q11: Closure Over Mutated Object
[INFO] Server started [ERROR] Something failed!
Trap: Closure captures reference to cfg, not a copy. Mutating cfg.level is reflected immediately.
Fix: Deep-copy or capture primitive:
Q12: Closure + setTimeout Output Chain
Immediate: 0 After 100ms: 1 After 200ms: 2
Explanation: Both setTimeout callbacks close over the same count. Each increments it.
Q13: Partial Application with Closures
function partial(fn, ...presetArgs) {
return function (...laterArgs) {
return fn(...presetArgs, ...laterArgs);
};
}
function add(a, b, c) {
return a + b + c;
}
const add5 = partial(add, 5);
const add5and10 = partial(add, 5, 10);
console.log(add5(10, 15)); // 30
console.log(add5and10(20)); // 3530 35
Q14: Closure Returning Closure
function a() {
let x = 10;
return function b() {
let y = 20;
return function c() {
console.log(x + y); // closes over both x and y
};
};
}
a()()();30
Q15: this Inside Closure vs Arrow Function
regular: undefined arrow: WoHoTech
Rule: Regular function inside setTimeout loses this. Arrow function inherits this from enclosing scope (lexically).
Interview Tips Summary 🎯
| Topic | What to Say |
|---|---|
| Definition | Function + lexical scope reference |
| Why it works | [[Environment]] record not GC'd while inner fn lives |
| Loop problem | var shared reference; fix with let or IIFE |
| Use cases | Counter, memoize, debounce, module, once, partial |
| Trap | Closure over object reference vs primitive |
| Memory | Closures prevent GC — nullify when done |
Practice Questions
- Implement
createMultiplier(n)— returns a function that multiplies byn. - Build a
memoizefunction for a recursive Fibonacci. - Write
debounce(fn, delay)using closures. - Create a
makeStack()withpush,pop,peekusing closures for private array. - Predict the output:
for(var i=0; i<5; i++) { (arr[i] = function(){ return i; })(); }
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Top 30 JavaScript Closure Interview Questions & Answers 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, interview, closure, questions
Related JavaScript Master Course Topics