US Trends

what is callback in javascript

A callback in JavaScript is a function you pass into another function so that it can be called later , usually after some work or an event has finished.

What is a callback in JavaScript?

In JavaScript, functions are “first-class,” meaning you can treat them like values: pass them as arguments, return them from other functions, and store them in variables.

A callback function is simply a function that you give to another function as an argument, and that other function “calls you back” when it’s ready (often after finishing some task or when an event happens).

In plain words: “Do X now, and when you’re done , run this other function.”

Simple callback example (step‑by‑step)

Imagine you want to greet someone, and after greeting them, you want to say goodbye.

js

function greet(name, callback) {
  console.log("Hello, " + name);
  callback(); // call the callback after greeting
}

function sayBye() {
  console.log("Goodbye!");
}

greet("Ajay", sayBye);

When greet("Ajay", sayBye) runs, this happens:

  1. greet prints "Hello, Ajay".
  2. greet then calls callback(), which is actually sayBye.
  3. sayBye prints "Goodbye!".

Here, sayBye is the callback because it’s passed into greet and executed later from inside greet.

You could also pass an anonymous function instead of a named one:

js

greet("Ajay", function () {
  console.log("This is an anonymous callback!");
});

Any function you pass that gets executed later by the “outer” function is a callback.

Why callbacks matter (especially in JS)

JavaScript is single-threaded and heavily event-driven , especially in browsers and Node.js. Callbacks are a core way to say “run this code when that thing finishes.”

Callbacks are commonly used for:

  • Asynchronous tasks
    • Network requests (fetching data from an API)
* Reading files (Node.js)
  • Timers
    • setTimeout, setInterval
  • Event handling
    • Clicks, key presses, form submissions, etc.

They help ensure that certain code doesn’t run until an operation (like a fetch or a timer) is complete.

Classic async callback examples

1. setTimeout callback

js

console.log("Before");

setTimeout(function () {
  console.log("This runs after 1 second");
}, 1000);

console.log("After");

Flow:

  • "Before" logs.
  • JavaScript sets a timer for 1000 ms.
  • "After" logs immediately.
  • After ~1 second, the callback passed into setTimeout runs.

The function you pass to setTimeout is the callback.

2. Event listener callback

js

const button = document.getElementById("myButton");

button.addEventListener("click", function () {
  console.log("Button clicked!");
});
  • addEventListener takes a callback function.
  • That callback runs every time the "click" event happens.

So this is like telling the browser: “Whenever the button is clicked, call this function.”

3. “Do something, then handle the result”

js

function myCalculator(num1, num2, myCallback) {
  const sum = num1 + num2;
  myCallback(sum);
}

function myDisplayer(result) {
  console.log("Result is:", result);
}

myCalculator(5, 5, myDisplayer);

Here:

  • myCalculator does some work (adds numbers).
  • It then calls myCallback with the result.
  • myDisplayer is the callback and decides how to use/display the result.

This is a common pattern in older callback‑style APIs.

Synchronous vs asynchronous callbacks

Not all callbacks are async by definition—“callback” just means “a function passed to another function.”

  • Synchronous callback : runs immediately inside the function.

    js
    
    const numbers = [1, 2, 3];
    
    numbers.forEach(function (n) {
      console.log(n);
    });
    

The callback passed to forEach runs right away for each element, no waiting involved.

  • Asynchronous callback : runs later, after some async operation completes (like setTimeout, network request, events).

The async usage is what people usually think of when they say “JavaScript callback.”

How callbacks look in real APIs

Networking example (conceptual)

Many older JS APIs use this pattern: (error, data) => { ... } as a callback.

js

function fetchData(url, callback) {
  // imagine some async request happening here
  // when it's done, it calls:
  // callback(error, data);
}

function handleResponse(error, data) {
  if (error) {
    console.error(error);
  } else {
    console.log("Data received:", data);
  }
}

fetchData("https://example.com/api", handleResponse);

Here:

  • handleResponse is the callback.
  • The fetch logic decides when to call it and with what arguments.

Callback advantages and drawbacks

Why callbacks are useful

  • Let you decouple “what to do” from “when/how it happens.”
  • Essential for events and async operations.
  • Very flexible: you can pass different callbacks to change behavior without changing the core logic.

The downside: “callback hell”

If you chain many async operations by nesting callbacks, code can become deeply indented and hard to read, often called “callback hell”:

js

getData((err, data) => {
  if (err) return console.error(err);
  process(data, (err, result) => {
    if (err) return console.error(err);
    console.log(result);
  });
});

To make this better, modern JavaScript uses Promises and async/await, which give a flatter, more linear style while still using callbacks under the hood.

How callbacks relate to Promises and async/await (2020s+ trend)

Even though Promises and async/await are popular now, they are essentially built on top of callbacks.

  • A Promise internally still uses callbacks to know what to do when an async operation finishes.
  • async/await is syntactic sugar over Promises.

Example transformation:

js

// Callback style
getData((err, data) => {
  if (err) return console.error(err);
  process(data, (err, result) => {
    if (err) return console.error(err);
    console.log(result);
  });
});

// Promise style
getData()
  .then(data => process(data))
  .then(result => console.log(result))
  .catch(err => console.error(err));

Even when you rarely write “raw callbacks” today, understanding them helps you understand how many JS abstractions actually work.

Quick mental model

You can think of a callback as leaving instructions with someone:

“Here’s my number. When you’re finished, call me back and tell me the result.”

In JavaScript:

  • Your number = the callback function.
  • The person doing the task = the function you call (like setTimeout, a fetch helper, an event listener registration).
  • The callback happens when they’re done or when an event occurs.

TL;DR – What is callback in JavaScript?

  • A callback is a function passed into another function to be executed later.
  • It’s heavily used for asynchronous code and event handling (timers, network requests, DOM events).
  • It can be synchronous (like forEach) or asynchronous (like setTimeout, API calls).
  • Too many nested callbacks lead to “callback hell,” which modern JS often replaces with Promises and async/await.

Information gathered from public forums or data available on the internet and portrayed here.