Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Callback Functions

A callback is a function passed into another function to be called later.

They are essential for async operations and array methods.

Why We Need It

Callbacks let you control when code runs, which is vital for events and async tasks.

Understanding callbacks is a foundation for promises and async/await.

Syntax

function doWork(callback) { ... }
doWork(() => { ... })

Basic Example

1. Simple callback

function run(task) {
  task();
}

run(() => console.log("Done"));

Pass a function to be called later.

Real World Example

2. Array callbacks

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);

console.log(doubled);

Array methods rely heavily on callbacks.

Multiple Use Cases

Functions as Arguments

A callback is a function passed into another function.

The receiver decides when to call it.

Async Patterns

Callbacks are common in asynchronous code like timers and event handlers.

They allow you to run logic after an async operation completes.

Avoid Callback Hell

Deeply nested callbacks can hurt readability.

Consider promises or async/await for complex flows.

More Examples

3. setTimeout callback

setTimeout(() => {
  console.log("Later");
}, 500);

Callbacks run after async timers.

4. Callback with data

function fetchData(done) {
  const data = { id: 1 };
  done(data);
}

fetchData((data) => console.log(data.id));

Callbacks can receive data from the caller.

Comparison

Without

const nums = [1, 2, 3];
const doubled = [];
for (const n of nums) {
  doubled.push(n * 2);
}

With

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);

Common Mistakes and Fixes

Too many nested callbacks

Refactor into named functions or use async/await.

Forgetting error handling

Use error-first callbacks or try/catch where appropriate.

Calling callback multiple times

Ensure the callback is called once per operation.

Interview Questions

What is a callback function?

A function passed to another function to be executed later.

Why are callbacks used in async code?

They allow logic to run after an async task completes.

How do you avoid callback hell?

Use named functions or switch to promises and async/await.

Practice Problem

Practice: Write a function that accepts a callback and runs it twice.

// TODO: function repeat(fn)

One Possible Solution

function repeat(fn) {
  fn();
  fn();
}

repeat(() => console.log("Hi"));

Frequently Asked Questions

What is a callback?

A function passed to another function to be executed later.

Are callbacks only for async?

No, they are also used for sync patterns like array methods.

What is callback hell?

Nested callbacks that are hard to read and maintain.

Try It Yourself

Try passing different callbacks to the function.