Understanding Callback Functions in JavaScript
In JavaScript, functions are not just something you run.
They can also be treated like values.
That means you can:
store them in variables
pass them as arguments
return them from other functions
This is where callback functions come in.
What is a Callback Function?
A callback is simply:
a function passed into another function and executed later
Example:
function greet(name, callback) {
console.log("Hello " + name)
callback()
}
function sayBye() {
console.log("Goodbye")
}
greet("Ishan", sayBye)
Here:
sayByeis passed as an argumentgreetdecides when to call it
So sayBye is a callback function
Why Callbacks Are Used
Callbacks are mainly used when something takes time.
JavaScript does not wait for tasks like:
fetching data
reading files
API calls
So instead of waiting, we pass a function to run after the task is done.
Example:
function fetchData(callback) {
setTimeout(() => {
console.log("Data received")
callback()
}, 2000)
}
function processData() {
console.log("Processing data")
}
fetchData(processData)
Here:
data comes after 2 seconds
then callback runs
Passing Functions as Arguments
This is the core idea behind callbacks.
function execute(fn) {
fn()
}
execute(function () {
console.log("Callback executed")
})
You are literally passing a function as data.
Common Real-Life Usage
Callbacks are used everywhere in JavaScript:
handling button clicks
API responses
timers (
setTimeout)event listeners
Example:
setTimeout(() => {
console.log("Runs after delay")
}, 1000)
The arrow function is a callback.
The Problem with Callbacks (Callback Nesting)
Callbacks are useful, but too many callbacks create problems.
Example:
doTask1(() => {
doTask2(() => {
doTask3(() => {
console.log("All tasks done")
})
})
})
This is called callback nesting.
Problems:
hard to read
hard to debug
messy structure
This is also known as:
How to Think About Callbacks
Instead of memorizing syntax, understand this:
A function can be passed like a value
Another function decides when to run it
That’s all a callback is.
One Line Summary
Callback = function passed into another function to run later
Conclusion
Callback functions are a core concept in JavaScript and are heavily used in asynchronous programming.
They allow us to control execution flow, especially when dealing with tasks that don’t complete immediately.
But overusing callbacks can lead to messy code, which is why modern JavaScript introduced Promises and async/await.