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:
greetprints"Hello, Ajay".greetthen callscallback(), which is actuallysayBye.sayByeprints"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
setTimeoutruns.
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!");
});
addEventListenertakes 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:
myCalculatordoes some work (adds numbers).- It then calls
myCallbackwith the result. myDisplayeris 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:
handleResponseis 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/awaitis 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 (likesetTimeout, 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.