JavaScript Closures and Scope Interview Questions (With Answers)
12 JavaScript closure and scope interview questions with clear answers and code: lexical scope, closures in loops, private variables, the module pattern, memoization, memory leaks and output-based puzzles.
Closures are the JavaScript topic interviewers use to check whether you really understand how functions and variables work. This post covers 12 closure and scope questions, from fresher-level definitions to the follow-ups asked of mid-level developers, each with a short answer, an explanation and code you can run.
Scope basics#
Q1. What is scope in JavaScript, and what kinds of scope are there?#
Answer: Scope decides where a variable can be accessed. JavaScript has global scope, function scope, block scope (for let, const and class inside {}) and module scope (top level of an ES module).
const appName = "JioCoder"; // global (or module) scope
function greet() {
const message = "Hi"; // function scope
if (true) {
let user = "Asha"; // block scope
var legacy = "visible"; // var ignores blocks → function scope
}
console.log(legacy); // "visible"
console.log(user); // ReferenceError: user is not defined
}Q2. What is lexical scope?#
Answer: Lexical (static) scope means a function's access to variables is decided by where it is written in the code, not where it is called from. When a variable isn't found locally, JavaScript looks in the enclosing scope, then the next one out, up to the global scope. This is the scope chain.
const name = "global";
function outer() {
const name = "outer";
function inner() {
console.log(name); // "outer": looked up where inner is defined
}
return inner;
}
const fn = outer();
fn(); // "outer", even though it's called from the global scopeQ3. What is the difference between var, let and const in terms of scope and hoisting?#
| var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted? | Yes, initialised to undefined | Yes, but in the temporal dead zone | Yes, but in the temporal dead zone |
| Re-declare in same scope | Allowed | Error | Error |
| Re-assign | Allowed | Allowed | Not allowed (object contents can still change) |
| Creates global object property | Yes (window.x) | No | No |
console.log(a); // undefined
var a = 1;
console.log(b); // ReferenceError: Cannot access 'b' before initialization (TDZ)
let b = 2;Closures#
Q4. What is a closure?#
Answer: A closure is a function bundled together with a reference to the scope it was created in. Because of that reference, the inner function can still read and update the outer function's variables after the outer function has returned.
function makeCounter() {
let count = 0; // would normally be garbage collected
return function () {
count += 1; // ...but the closure keeps it alive
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
const another = makeCounter();
another(); // 1 → each call to makeCounter creates a fresh scope"Every function in JavaScript forms a closure. It remembers the variables from the place it was defined, by reference, not by copying their values."
Q5. What does this code print, and how do you fix it?#
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}Answer: It prints 3 3 3. There is only one i (function-scoped var), and by the time the timers fire the loop has finished and i is 3. All three callbacks close over the same variable.
Fixes:
// 1. let creates a new binding for each iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0 1 2
}
// 2. An IIFE captures the current value (the pre-ES6 fix)
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 100);
})(i);
}
// 3. setTimeout passes extra arguments to the callback
for (var i = 0; i < 3; i++) {
setTimeout((j) => console.log(j), 100, i);
}Q6. How do you create private variables with closures?#
Answer: Keep the data in a function's local scope and return only the functions that are allowed to touch it. Nothing outside can read or change the variable directly.
function createBankAccount(initial) {
let balance = initial; // private
return {
deposit(amount) {
if (amount <= 0) throw new Error("Invalid amount");
balance += amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const acc = createBankAccount(100);
acc.deposit(50); // 150
acc.balance; // undefined: not reachable from outsideFollow-up: modern classes can also use #private fields, but closures were the original (and still common) way to hide state.
Q7. What is the module pattern, and how is it related to closures?#
Answer: The module pattern uses an IIFE (immediately invoked function expression) to create a private scope once and return a public API. It was the standard way to avoid polluting the global scope before ES modules.
const Cart = (function () {
const items = []; // private
function total() {
return items.reduce((sum, i) => sum + i.price, 0);
}
return {
add(item) { items.push(item); },
total,
count: () => items.length,
};
})();
Cart.add({ name: "Book", price: 299 });
Cart.total(); // 299Q8. Write a function once(fn) that runs fn only the first time.#
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
const init = once(() => { console.log("init!"); return 42; });
init(); // logs "init!", returns 42
init(); // returns 42, no logExplanation: called and result live in the closure, so every call to the returned function shares them. Using fn.apply(this, args) preserves this and all arguments.
Q9. Implement memoize(fn) using a closure.#
function memoize(fn) {
const cache = new Map(); // private cache per memoized function
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const value = fn.apply(this, args);
cache.set(key, value);
return value;
};
}
const slowSquare = (n) => { for (let i = 0; i < 1e7; i++); return n * n; };
const fastSquare = memoize(slowSquare);
fastSquare(9); // slow the first time
fastSquare(9); // instant: served from the cacheMention the trade-offs: JSON.stringify keys don't work for functions or circular objects, and an unbounded cache can grow forever (use an LRU limit in production).
Advanced follow-ups#
Q10. Can closures cause memory leaks?#
Answer: Yes. A closure keeps its outer variables reachable, so as long as the closure itself is reachable (for example as an event listener, timer callback or cache entry), those variables can't be garbage collected.
function attach() {
const hugeData = new Array(1_000_000).fill("x");
document.getElementById("btn").addEventListener("click", () => {
console.log(hugeData.length); // closure keeps hugeData alive
});
}
// Fix: remove the listener when no longer needed, or avoid capturing large data:
// const len = hugeData.length; and use len inside the handlerRead more in JavaScript memory leaks and garbage collection.
Q11. What is currying, and how do closures make it possible?#
Answer: Currying turns a function of many arguments into a chain of functions that each take one argument. Each returned function closes over the arguments received so far.
const add = (a) => (b) => (c) => a + b + c;
add(1)(2)(3); // 6
// Generic curry
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...next) => curried.apply(this, [...args, ...next]);
};
}
const volume = curry((l, w, h) => l * w * h);
volume(2)(3)(4); // 24
volume(2, 3)(4); // 24Q12. Predict the output.#
function createFns() {
const fns = [];
for (var i = 0; i < 3; i++) {
fns.push(function () { return i * 2; });
}
return fns;
}
const [a, b, c] = createFns();
console.log(a(), b(), c());
let x = 10;
function show() { console.log(x); }
function run() { let x = 20; show(); }
run();Answer: 6 6 6, then 10.
- All three functions share the single
var i, which is 3 after the loop, so each returns 6. showwas defined at the top level, so it reads the globalx(lexical scope), not thexinsiderun.
Quick revision#
| Concept | One-line answer |
|---|---|
| Lexical scope | Variable access depends on where code is written |
| Closure | Function + reference to its outer scope |
| var in loops | One shared binding; use let for one per iteration |
| Private state | Local variables exposed only through returned functions |
| Memory risk | Long-lived closures keep captured data alive |
Want more practice? Try the broader JavaScript interview questions for freshers and see closures in action in debounce vs throttle.
Key takeaways#
- JavaScript uses lexical scope: a function sees the variables from where it was defined.
- A closure lets an inner function keep using outer variables after the outer function returns.
varin a loop shares one binding;letcreates a new one per iteration.- Closures power private state, the module pattern, once(), memoize, currying and debounce.
- Long-lived closures can leak memory, so remove listeners and avoid capturing large objects.