Closures are one of the most frequently tested concepts in JavaScript technical interviews. Understanding how closures work under the hood helps candidates write cleaner stateful functions and spot memory retention bugs.
What is a Closure?
A closure is created whenever a function is defined inside another function, granting the inner function access to the outer function's variable environment (lexical scope).
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const closureFn = outerFunction("Hello");
closureFn("World"); // Outer: Hello, Inner: WorldPractical Applications of Closures
1. Private State & Data Encapsulation
#private), closures were the primary mechanism for creating private variables.function createBankAccount(initialBalance) {
let balance = initialBalance; // Private state
return {
deposit(amount) {
if (amount > 0) balance += amount;
return balance;
},
withdraw(amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return balance;
}
return "Insufficient funds";
},
getBalance() {
return balance;
}
};
}2. Function Memoization
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}*Practice the Memoize coding task on Pairlet.*
Classic Interview Loop Gotcha
What does the following code log?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Logs: 3, 3, 3Why? var is function-scoped. All three callbacks share the exact same i reference, which is 3 by the time the timers fire.
Fix 1: Use let (Block Scope)
javascript
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
} // Logs: 0, 1, 2
``Fix 2: Create a Closure via IIFE
javascript
for (var i = 0; i < 3; i++) {
((index) => {
setTimeout(() => console.log(index), 100);
})(i);
} // Logs: 0, 1, 2
``Practice Closure Problems Live
Frequently Asked Questions
What is a closure in simple terms?
A closure is a function that remembers and accesses variables from its outer lexical scope even after that outer function has finished executing.
Conduct Live Coding Interviews in the Browser
No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.