Callback
A callback is a function passed to another function to run later. Learn what callbacks are, why they're useful, and how JavaScript's event loop works.
A callback is a function passed to another function to run later. Learn what callbacks are, why they're useful, and how JavaScript's event loop works.
A callback is a function you pass as an argument to another function, to be called at a later point.
function greet(name, callback) { const message = `Hello, ${name}!`; callback(message);}
greet("Reza", (msg) => { console.log(msg); // Hello, Reza!});greet does its work, then calls the function you passed in. You decide what happens with the result.
JavaScript is single-threaded — it can only do one thing at a time. But some operations take time: fetching data, reading a file, waiting for a timer. Blocking everything while you wait would freeze the page.
Instead, you start the operation and pass a callback. JavaScript continues with other work and calls your function when the operation finishes.
setTimeout(() => { console.log("this runs after 1 second");}, 1000);
console.log("this runs immediately");// Output:// this runs immediately// this runs after 1 secondYou’ve already been using callbacks with event listeners:
button.addEventListener("click", () => { console.log("clicked");});The second argument is a callback — run this function when the click happens.
And with array methods:
[1, 2, 3].forEach((n) => console.log(n));forEach takes a callback and runs it for each item.
When callbacks nest deeply, readability suffers:
getUser(id, (user) => { getPosts(user.id, (posts) => { getComments(posts[0].id, (comments) => { // three levels deep — and this is a simple case }); });});Promises and async/await were invented to solve this. But understanding callbacks first makes those patterns make sense.