17 / 18

Explain the concept of a 'callback function' and provide an example of its usage.

A callback function is a function that is passed as an argument to another function and is executed after a certain task is completed. It's often used to handle asynchronous operations, like when fetching data from a server.

javascript
Difficulty: 3/10
Topics: higher-order functions, asynchronous programming, event handling

Scenario Questions

0-2 years experience
  1. 1

    Write a function fetchData(url, callback) that uses setTimeout to simulate an async request and then calls the callback with mock data. How would you verify it works?

  2. 2

    If the callback you receive throws an exception, what happens to fetchData's execution? How could you protect against it?

2-5 years experience
  1. 1

    We need a debounce utility that takes a function and a wait time and returns a debounced version using callbacks. Walk me through your implementation and any trade‑offs.

  2. 2

    During a review you notice a function that accepts a callback but sometimes calls it twice, causing duplicate UI updates. How would you debug and fix the issue?

  3. 3

    Why might a callback‑based API break when you start using Promise‑based code elsewhere? Explain the difference in flow.

5-8 years experience
  1. 1

    Our event system stores callbacks in an array and we’re seeing memory growth under load. How would you redesign the callback handling to prevent leaks and improve performance?

  2. 2

    Design an async task runner that executes an array of callbacks in series, handling errors and optional timeouts. What edge cases do you need to guard against?

  3. 3

    When integrating a third‑party library that uses callbacks, how would you ensure proper cancellation and avoid dangling references in a large SPA?

8+ years experience
  1. 1

    We’re migrating a legacy codebase full of nested callbacks to a Promise/async‑await architecture. What migration strategy would you propose to minimize risk and keep backward compatibility?

  2. 2

    Design a cross‑team event bus that lets modules register callbacks with type safety and versioning. What architectural decisions keep it scalable and maintainable?

  3. 3

    How would you assess the impact of replacing callback‑based streaming APIs with reactive streams on latency and resource usage across our microservices?

Follow-up Questions

  • Can you compare callbacks with Promises for error handling?
  • What are common pitfalls when callbacks are used inside loops?
  • How would you guarantee a callback is invoked exactly once?