Skip to content
RED SAGSkills
easyFrontend Developer interview question

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.

Start mock interview

More easy Frontend Developer questions