Callbacks in JavaScript: Why They Exist

A callback is a function you pass into another function so that it can decide when to run it. Not immediately Only when the outer function chooses.
function greet(name) {
return `Hello, ${name}`;
}
function processUserInput(callback) {
const name = "Rachit";
// callback is just a function reference here
// we decide when to execute it
return callback(name);
}
// passing function, not calling it
const result = processUserInput(greet);
console.log(result); // Hello, Rachit
Why Callbacks Exist
JavaScript doesn’t wait around for slow tasks.If something takes time, like a network request or delay, blocking the whole program is a bad idea.So instead of waiting, we say: “Run this function when you're done.” That “this function” is the callback.
Where You Actually Use Callbacks
Callback functions are primarly used in async functions where we send rquest to other network or you could say when promise is resolved the callback is calleld
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
const data = { id: 1, name: "Rachit" };
callback(data);
}, 2000);
}
fetchData((data) => {
console.log("Data received:", data);
});
console.log("This runs first");
The Problem: Callback Hell
Callbacks scale badly when tasks depend on each other.
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
// this keeps going...
}, 1000);
}, 1000);
}, 1000);
What’s wrong here:
Hard to read
Hard to debug
Error handling becomes messy
Logic gets buried inside nesting
This is what people call “callback hell.”
What Comes Next
Callbacks aren’t wrong. They’re just not scalable.
That’s why JavaScript moved to:
Promises
async/await




