What is a closure in JavaScript? Give a practical example of where you use one.
What the interviewer wants to hear
- A closure is a function that remembers variables from the scope where it was created
- The inner function can use those variables even after the outer function has returned
- Used for private state, factories, and callbacks such as event handlers
- React hooks and handlers rely on closures, which explains stale value bugs
Model answer
A closure is a function bundled together with the variables from the scope where it was defined. Because of that, an inner function can keep reading and updating those variables even after the outer function has finished running. A simple example is a counter factory: function makeCounter() { let count = 0; return () => ++count }. Each counter returned has its own private count that no other code can touch. I use closures all the time without thinking about it: event handlers that remember an item id, debounce helpers that keep a timer id between calls, and module patterns for private state. In React, every render creates new handler functions that close over that render’s props and state. That is also the source of stale closure bugs, for example a setInterval callback created in an effect with an empty dependency array always seeing the first value. Knowing how closures work makes those bugs easy to explain and fix.
Can you answer it under time pressure?
Take a timed easy round and get scored on every answer.
More easy Frontend Developer questions
- Explain the CSS box model. What is the difference between content-box and border-box?
- What is the difference between var, let and const in JavaScript?
- What is semantic HTML and why does it matter?
- In React, what is the difference between props and state?
- How do you make a web page responsive for mobile, tablet and desktop?
- What is the difference between Flexbox and CSS Grid, and when would you use each?
- How do you make a form accessible?
- A button on a page does not work when clicked. How would you use browser DevTools to find the problem?
- What is a Promise, and how does async/await relate to it?