Callback Functions in JavaScript 🔄


By Ronak Wanjari, Intern Devsync
While working on async tasks at DevSync, I kept hearing the word “callback” — especially in functions like setTimeout()
, APIs, and file operations.
So here’s a simple breakdown of callback functions — with examples you’ll actually use.
🔹 What is a Callback?
A callback function is a function passed as an argument to another function — and it’s called later when something finishes.
function greet(name, callback) {
console.log("Hi " + name);
callback();
}
function done() {
console.log("Greeting complete!");
}
greet("DevSync", done);
👉 Output:
Hi DevSync
Greeting complete!
🔹 Real Example: setTimeout
uses Callback
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
Here, the arrow function is a callback — it runs after the timeout.
🔹 Synchronous vs Asynchronous Callbacks
🟢 Synchronous:
function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(5, 3, (sum) => {
console.log("Sum is", sum); // Sum is 8
});
🟠 Asynchronous:
function fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
fetchData((data) => {
console.log(data); // Data loaded
});
🔹 Why Use Callbacks?
Handle async operations (API calls, timers, I/O).
Keep code modular and reusable.
Avoid repeating logic.
⚠️ Callback Hell
Too many nested callbacks look messy:
doA(() => {
doB(() => {
doC(() => {
console.log("All done!");
});
});
});
🧠 Solution? Use Promises or async/await (but that's another blog 😉)
🔚 Conclusion
At Devsync , I used callbacks daily — from button click handlers to API responses. They're core to writing good JavaScript, especially when things aren't instant (like user input or data fetching).
✅ Quick Recap:
A callback is a function passed to another function.
Used a lot in async code (like
setTimeout
, APIs).Avoid nesting too deep — use Promises later!
📌 Want more JavaScript breakdowns from a dev intern’s POV?
Follow me for more blogs and real-use code!
🔗 Devsync
Subscribe to my newsletter
Read articles from ronak wanjari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
