05 / 10

How do closures enable event handling

Difficulty: 5/10
closures, event handling, scope
Event Handling: We can use a closure to encapsulate the necessary data and logic for handling the event. This allows you to maintain context and access relevant variables when the event is triggered.

Scenario Questions

0-2 years experience

  1. 1You have three buttons and need each click to log its position (0, 1, 2). How would you write the click handler using a closure?
  2. 2If you write the handler inside a for loop without a closure, what will be logged when any button is clicked and why?
  3. 3Explain what happens when the handler accesses a variable defined outside the function after the outer function has finished executing.

2-5 years experience

  1. 1We have a dynamic form where each input validates against the form's current state, but the code uses a global variable and breaks when two forms are on the page. How would you rewrite the listeners with closures to isolate each form's state?
  2. 2During debugging you notice a setTimeout inside a click handler always sees an outdated value of a counter. Why does this happen and how can a closure fix it?
  3. 3What are the trade‑offs between creating a separate closure for each element versus using a single shared handler that reads data attributes?

5-8 years experience

  1. 1You are building a reusable UI component library that must support thousands of widgets, each with its own event callbacks. How would you design the internal event system using closures to keep per‑widget state while minimizing memory overhead?
  2. 2A memory leak has been reported in a dashboard where event listeners are never removed. How can the way you use closures contribute to the leak, and what pattern would you apply to avoid it?
  3. 3Discuss how closures interact with async event streams like RxJS and what considerations you’d make for back‑pressure and garbage collection.

8+ years experience

  1. 1Our legacy codebase uses a global callback registry. We want to migrate to a modular architecture. How would you restructure the event handling layer using closures to enforce encapsulation across multiple teams, and what governance would you put in place?
  2. 2When designing a cross‑team UI framework, you need to decide whether to expose event APIs that rely on closures or on explicit context objects. What are the long‑term maintenance and performance implications of each choice?
  3. 3If you need to support server‑side rendering where event handlers are serialized, how would you handle closures that capture runtime state?

Follow-up Questions

  • What changes if you use var instead of let for the loop variable?
  • How does the closure affect memory usage when many listeners are attached?
  • Can you refactor the handler to avoid a closure while preserving functionality?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.