JavaScript Callback Functions – Complete Notes
What is a Callback Function?
A callback is a function passed as an argument to another function, to be executed later.
“A callback gives you control over when a function should be executed.”
Why Use Callbacks?
• Asynchronous behavior (e.g., handling API calls, reading files)
• Reusability (function logic reused with different callbacks)
• Control flow (you control what happens after a task completes)
Basic Syntax
javascript
CopyEdit
function greet(name, callback) {
console.log("Hello " + name);
callback();
function sayGoodbye() {
console.log("Goodbye!");
greet("Subhadip", sayGoodbye);
Here, sayGoodbye is passed as a callback to greet.
Anonymous Callback
javascript
CopyEdit
greet("Subhadip", function () {
console.log("See you later!");
});
Arrow Function Callback
javascript
CopyEdit
greet("Subhadip", () => {
console.log("Take care!");
});
Real-World Examples
1. Array Methods (Map, Filter, ForEach use callbacks)
javascript
CopyEdit
let numbers = [1, 2, 3];
numbers.forEach((num) => {
console.log(num * 2);
});
2. setTimeout / setInterval
javascript
CopyEdit
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
3. Event Listeners
javascript
CopyEdit
document.getElementById("btn").addEventListener("click", () => {
console.log("Button clicked!");
});
Synchronous vs Asynchronous Callbacks
Type Example Description
Synchronous forEach, map Executes immediately
Asynchronous setTimeout, fetch Executes later, after a task
Callback Hell (Pyramid of Doom)
Too many nested callbacks → hard to read & maintain.
javascript
CopyEdit
doTask1(() => {
doTask2(() => {
doTask3(() => {
console.log("Done");
});
});
});
Solution: Use Promises or Async/Await.
Creating Your Own Callback-Based Function
javascript
CopyEdit
function calculate(a, b, operation) {
return operation(a, b);
function add(x, y) {
return x + y;
console.log(calculate(4, 5, add)); // 9
Benefits of Callback Functions
• More modular code
• Reusability of logic
• Foundation of async programming
Drawbacks
• Difficult to manage when deeply nested (Callback Hell)
• Harder debugging compared to Promises/Async-Await