JavaScript Course
JavaScript
/
Beginner

Callbacks

Definition

A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Explain Like I'm New

Imagine ordering food at a restaurant. You don't stand at the counter waiting while they cook. You give the cashier your phone number (the callback). You go sit down (continue executing code), and when the food is ready, they call your number to let you know.

Real World Example

Passing a function to `setTimeout` or `addEventListener('click', handleClick)`. The `handleClick` function is a callback.

Common Use Cases

  • •Asynchronous execution
  • •Event handling
  • •Array methods (map, filter)

Interactive Example

function fetchData(callback) {
  console.log('1. Fetching data...');
  setTimeout(() => {
    const data = { id: 1, name: 'Alice' };
    // Execute the callback function passed as an argument
    callback(data);
  }, 2000);
}

// The anonymous function here is the callback
fetchData((result) => {
  console.log('2. Data received:', result.name);
});
console.log('3. I run immediately without waiting!');

Interview Questions

basic

  • What is a higher-order function in relation to callbacks?

intermediate

  • What is the difference between a synchronous and asynchronous callback?

advanced

  • How do callbacks handle errors in Node.js?

Flash Cards

Question

Synchronous vs Asynchronous callback?

Click to reveal answer
Answer

A synchronous callback runs immediately before the outer function completes (e.g., `[].map(cb)`). An asynchronous callback is registered and executed later, after the outer function has returned (e.g., `setTimeout(cb, 1000)`).

Question

How do callbacks handle errors in Node.js?

Click to reveal answer
Answer

Node.js uses an 'Error-First Callback' pattern. The first argument of the callback is reserved for the error object. If successful, the first argument is `null` and the data is passed in the second argument: `fs.readFile('data.txt', (err, data) => {})`.