what is a callback function in javascript?
A callback function in JavaScript is a function you pass into another function so that the outer function can call it later, often after some work is done.
Quick Scoop: Plain-English Definition
Think of a callback as leaving your phone number with a friend:
âYou do X, and when youâre done, call me back with the result.â In JavaScript:
- You define a function (the callback).
- You pass it as an argument to another function.
- That other function decides when to execute it (immediately, after a delay, when an event happens, when data arrives, etc.).
A Tiny Code Example
Synchronous callback (runs immediately)
js
function greet(name) {
console.log("Hello, " + name + "!");
}
function processUserInput(callback) {
const name = "Alice";
callback(name); // call the callback
}
processUserInput(greet); // passes greet as a callback
greetis the callback.processUserInputreceivesgreetas a parameter and calls back withcallback(name).
This is a synchronous callback because it executes right away during the function call.
Asynchronous callbacks (super common in JS)
JavaScript is big on async tasks: timers, network calls, file operations, user events, etc.
Example: setTimeout
js
setTimeout(function () {
console.log("This runs after 1 second");
}, 1000);
- The anonymous function is the callback.
setTimeoutwaits 1000 ms, then calls the callback.
Example: Event listener
js
const button = document.getElementById("myButton");
button.addEventListener("click", function (event) {
console.log("Button clicked!");
});
- The function passed to
addEventListeneris a callback. - The browser calls it when the click event happens.
Why callbacks matter
Callbacks are a core part of JavaScriptâs design, especially for browser and server code.
They help you:
- Run code after something finishes (like a fetch request).
- Keep long-running tasks from blocking the main thread.
- React to events (clicks, keypresses, network responses, timers).
A common async pattern:
js
function fetchData(url, callback) {
// imagine this does an async request
// and later calls callback(error, data)
}
function handleResponse(error, data) {
if (error) {
console.error(error);
} else {
console.log("Data received:", data);
}
}
fetchData("https://example.com", handleResponse);
handleResponseis the callback that runs when the data (or error) is ready.
A quick note on âcallback hellâ
If you keep nesting callbacks inside callbacks, code can turn into a deeply indented pyramid:
js
loadScript("1.js", function (error, script) {
if (error) return handleError(error);
loadScript("2.js", function (error, script) {
if (error) return handleError(error);
loadScript("3.js", function (error, script) {
if (error) return handleError(error);
// continue...
});
});
});
This is often called âcallback hellâ and is one of the reasons Promises and async/await became popular alternatives for handling async logic.
TL;DR
- A callback function is a function you pass into another function so it can be executed later.
- Used heavily for:
- Event handling (
addEventListener) - Timers (
setTimeout) - Async operations (network requests, file I/O).
- Event handling (
- Theyâre essential to how JavaScript handles asynchronous behavior.
If youâd like, I can next show you how to âconvertâ a callback-based function into a Promise/asyncâawait version for more modern-style code.