JavaScript Interview Question #76
What is a callback function in JavaScript?
Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate
Quick Interview Answer
A callback is a function passed to another function so it can be executed later or as part of that function's operation. Callbacks are fundamental to JavaScript APIs such as event handling, timers, array methods, and asynchronous operations.
Detailed Explanation
A callback is a function passed to another function so it can be executed later or as part of that function's operation. Callbacks are fundamental to JavaScript APIs such as event handling, timers, array methods, and asynchronous operations.
Callbacks may execute synchronously, as with Array.map, or asynchronously, as with many browser APIs. The important point is that the receiving code decides when and how the callback is invoked.
Code Example
function processUser(name, callback) {
const message = `Hello ${name}`;
callback(message);
}
processUser("Asif", message => {
console.log(message);
});