TechnicalMedium JavaScript
What is a closure in JavaScript? Give a practical example.
Asked for Frontend Developer, Full-Stack Developer, Mobile Developer
Why they ask this: Closures power callbacks, React hooks, module patterns and data privacy, so they show how well you know the language.
Answer
A closure is a function together with the variables from the scope where it was created. The inner function keeps access to those variables even after the outer function has returned.
js
function makeCounter() {
let count = 0; // private to the closure
return {
increment: () => ++count,
current: () => count,
};
}
const counter = makeCounter();
counter.increment();
counter.increment();
console.log(counter.current()); // 2Practical uses:
- Data privacy:
countcannot be changed from outside. - Function factories, for example
const add5 = makeAdder(5). - Callbacks and event handlers that remember values.
- React hooks: every render's handlers close over that render's state, which is why stale state bugs happen.
Can you explain this in your own words?