What are callbacks in JavaScript?

HighEasyJavascript
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

A callback is a function passed as an argument to another function to be executed later, often after a task is completed. Covers: async, callbacks, event loop, functions, higher order functions.

Answer

The Core Idea

A callback is simply a function passed into another function as an argument, to be called back later when a certain task finishes. It’s a fundamental pattern in JavaScript, especially in asynchronous programming.

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
16 / 61