wasAsked.

What is a closure in JavaScript?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · JavaScript

Community answers

Posted by wasAsked editorial collection

A closure is a function that remembers and can access variables from the scope where it was created, even after that outer function has finished executing. In JavaScript, every function forms a closure over its surrounding lexical scope. Basic example function makeCounter() { let count = 0; // private to this function call return function increment() { count++; // still accessible after makeCounter returned return count; }; } const counter = makeCounter(); counter(); // 1 counter(); // 2 const another = makeCounter(); another(); // 1 — each call to makeCounter creates a separate closure with its own count makeCounter has finished running, but count is not garbage-collected because the returned increment function still references it. How it works - JavaScript uses lexical scoping: a function's access to variables is determined by where it is written in the code. - When a function is created, it keeps a reference to its outer environment (the scope chain). Inner functions look up variables in their own scope, then outer scopes, up to the global scope. Practical uses 1. Data privacy and encapsulation (module pattern) function createBankAccount(initial) { let balance = initial; return { deposit(amount) { balance += amount; return balance; }, getBalance() { return balance; }, }; } const account = createBankAccount(100); account.deposit(50); // 150 account.balance; // undefined — not directly accessible (Modern classes can also use private fields: #balance.) 2. Function factories and partial application const multiplyBy = factor => n => n * factor; const double = multiplyBy(2); double(5); // 10 3. Event handlers and callbacks function setupButton(button, message) { button.addEventListener('click', () => alert(message)); // remembers message } 4. Memoisation function memoize(fn) { const cache = new Map(); return x => cache.has(x) ? cache.get(x) : (cache.set(x, fn(x)), cache.get(x)); } 5. React hooks rely on closures: event handlers and effects capture the state values from the render in which they were created. Classic interview question: closures in loops for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // prints 3, 3, 3 var is function-scoped, so all three callbacks share the same i, which is 3 when they run. Fix with let (block-scoped: a new binding per iteration): for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // prints 0, 1, 2 Pitfalls - Stale closures in React: a callback or effect may use an outdated state value captured from an earlier render. Fix with correct dependency arrays, functional state updates (setCount(c => c + 1)) or refs. - Memory leaks: closures keep referenced variables alive. Long-lived closures (global event listeners, timers) that capture large objects prevent garbage collection; remove listeners and clear timers when no longer needed. Interview summary: "A closure is a function bundled with references to the variables of the scope where it was defined. It lets functions keep private state, build factories and callbacks, and explains behaviours like the var-in-loop problem and stale state in React."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics