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?