Callbacks in JavaScript: Why They Exist
Functions Are Values in JavaScript
In JavaScript, functions can be:
Stored in variables
Passed as arguments
Returned from other functions
Example
function greet() {
console.log("Hello");
}
const sayHello = greet;
sayHello();
What Is a Callback Function?
A callback is a function passed into another function to be executed later.
Basic Callback Example
function processUser(callback) {
console.log("Processing user");
callback();
}
function completed() {
console.log("Completed");
}
processUser(completed);
Output
Processing user Completed
Function Calling Another Function Flow
flowchart LR
A[processUser()] --> B[callback()]
Passing Functions as Arguments
Functions can be passed like normal values.
Example
function calculate(a, b, operation) {
return operation(a, b);
}
function add(x, y) {
return x + y;
}
console.log(calculate(10, 5, add));
Output
15
Why Callbacks Exist
Callbacks are heavily used in asynchronous programming.
They allow JavaScript to continue running while waiting for slow tasks.
Examples:
File reading
API requests
Database queries
Timers
Synchronous Example
console.log("Start");
console.log("Task");
console.log("End");
Output
Start Task End
Each line waits for the previous line.
Asynchronous Example With Callback
console.log("Start");
setTimeout(() => {
console.log("Task completed");
}, 2000);
console.log("End");
Output
Start End Task completed
Why This Happens
setTimeout() is asynchronous.
JavaScript does not wait for it to finish.
Instead:
It registers the callback
Continues executing other code
Executes callback later
Async Callback Flow
Common Callback Scenarios
Callback Example in Event Handling
button.addEventListener("click", () => {
console.log("Button clicked");
});
The function runs later when the event happens.
Callback Example in File Reading
const fs = require("fs");
fs.readFile("notes.txt", "utf8", (error, data) => {
console.log(data);
});
The callback executes after file reading finishes.
Benefits of Callbacks
Problem With Nested Callbacks
When many async operations depend on each other, callbacks become deeply nested.
Nested Callback Example
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);
Nested Callback Execution Flow
Problems With Callback Nesting
This Problem Is Called
Callback Hell
or
Pyramid of Doom
Modern Alternatives
To solve callback problems, JavaScript introduced:
Promises
Async/Await
Simple Callback Rule
A callback means:
"Run this function later"
Practice Exercise
function greetUser(name, callback) {
console.log(`Hello ${name}`);
callback();
}
function finished() {
console.log("Greeting completed");
}
greetUser("Ali", finished);
Key Takeaways
Callbacks are fundamental to JavaScript because the language relies heavily on asynchronous behavior.
Even though modern JavaScript often uses:
Promises
Async/Await
understanding callbacks is important because many APIs and libraries still use them internally.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!