What are callbacks in JavaScript?

HighEasyJavascript
Quick Answer

Callbacks are the original control-flow hook in JavaScript. The production issues are inversion of control, callback hell, and debugging legacy async code that cannot cancel or compose cleanly.

Answer

The Core Idea

A callback is a function you hand to other code so it can run later. That sounds simple, but the production/debug issue is inversion of control: another API decides when your function runs, what error path it takes, and whether it can be canceled or composed cleanly.

JAVASCRIPT
// Example: synchronous callback
function greet(name) {
  console.log('Hello, ' + name);
}

function processUserInput(callback) {
  const name = 'Alice';
  callback(name);
}

processUserInput(greet); // Hello, Alice
                  

Callbacks in Asynchronous Code

Callbacks are also used to handle tasks that take time (like network requests or file loading), so the program can keep running while waiting for them to finish.

JAVASCRIPT
console.log('Start');

setTimeout(function() {
  console.log('This runs later');
}, 1000);

console.log('End');
// Output: Start → End → This runs later
                  

Concept

Explanation

Example

Synchronous Callback

Executed immediately during the function call.

[1,2,3].forEach(num => console.log(num));

Asynchronous Callback

Executed later, after a delay or async operation finishes.

fs.readFile('data.txt', callback);

Callback Hell

When many callbacks are nested inside each other, making code hard to read.

getData(() => getMore(() => getEvenMore()));

Common callback types and use cases.

Practical notes

Watch for edge case behavior, common pitfalls, and trade-offs between clarity and performance. Mention accessibility and testing considerations when the concept affects UI output or event timing.

Still so complicated?

Think of callbacks like leaving your phone number with someone: you don’t wait on the line — they’ll call you back when they’re ready.

Summary
  • A callback is a function passed as an argument to another function.
  • Allows asynchronous and event-driven behavior.
  • Can cause 'callback hell' when deeply nested — use Promises or async/await instead.
  • Core part of how JavaScript handles non-blocking operations.
Similar questions
Guides
Preparing for interviews?

Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.