Understanding Callback Functions in JavaScript
In JavaScript, you can use functions like regular values. You can store them in variables, pass them as arguments to other functions, or return them from functions. This feature makes callback functions possible.
function sayHello() {
console.log("Hello!");
}
function runFunction(fn) {
fn();
}
runFunction(sayHello);What is a Callback Function?
A callback function is a function that is passed as an argument to another function, and it is usually invoked inside that function to complete some kind of routine or action.
In simple terms:
A callback is a function that gets called after another function finishes its task.
Basic Example
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Ali", sayBye);Output:
Hello, Ali
Goodbye!Here, sayBye is passed as a callback and is called after greeting the user.
Why Use Callbacks?
Get One Minute Coder’s stories in your inbox
Join Medium for free to get updates from this writer.
Callbacks are mainly used to:
- Handle asynchronous operations (like data fetching)
- Allow flexibility in how a function behaves
- Avoid code repetition
Callbacks in Asynchronous Code
Callbacks are especially useful for asynchronous operations like reading files, making HTTP requests, or using timers.
setTimeout(function () {
console.log("This runs after 2 seconds");
}, 2000);The anonymous function here is a callback passed to setTimeout.
Named vs Anonymous Callbacks
Named Callback:
function done() {
console.log("Task finished.");
}
doSomething(done);Anonymous Callback:
doSomething(function () {
console.log("Task finished.");
});Common Use Case: Array Methods
const numbers = [1, 2, 3, 4];numbers.forEach(function (num) {
console.log(num * 2);
});Here, the function passed to forEach is a callback executed for each element.
Conclusion
Callback functions are a powerful way to make JavaScript code more dynamic and responsive. They are essential for handling asynchronous behavior and for building flexible, reusable functions.
As you go deeper into JavaScript, you’ll also encounter Promises and async/await, which are modern ways of handling asynchronous code — often built on top of callbacks.





