Callback Functions in JavaScript
JavaScript is a powerful programming language that supports functions as first-class citizens. This means functions can be stored in variables, passed as arguments, and returned from other functions. One important concept based on this is the callback function.
What is a Callback Function?
- A callback function is a function that is passed as an argument to another function and is executed later.
- In simple words, one function “calls back” another function after completing its task.
Syntax
function mainFunction(callback) {
callback();
}
function sayHello() {
console.log("Hello");
}
mainFunction(sayHello);
Output
Hello
Here:
-
sayHellois the callback function -
mainFunctionis the function that receives and executes it
Why Do We Use Callback Functions?
Callbacks are mainly used for:
- Reusing code
- Performing actions after another task finishes
- Handling asynchronous operations
- Event handling
Example 1: Simple Callback
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function message() {
console.log("Welcome to JavaScript");
}
greet("Kavitha", message);
Output
Hello Kavitha
Welcome to JavaScript
Here, after greeting the user, the message() function is called.
Example 2: Callback with Calculation
function add(a, b, callback) {
let result = a + b;
callback(result);
}
function display(result) {
console.log("Sum is: " + result);
}
add(10, 20, display);
Output
Sum is: 30
The result is passed to another function using a callback.
Example 3: Callback with setTimeout()
This is one of the most common examples.
console.log("Start");
setTimeout(function () {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
Output
Start
End
This runs after 2 seconds
Even though the timeout function is written in the middle, it executes later.
This happens because JavaScript handles it asynchronously.
Real-Time Use of Callback Functions
Callbacks are used in:
- Button click events
- API responses
- Timers
- Array methods like
forEach(),map(),filter()
Example: forEach()
let numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
Here, the function inside forEach() is a callback.
Important Note
When passing a callback, do not use parentheses.
Correct:
mainFunction(sayHello);
Wrong:
mainFunction(sayHello());
Because sayHello() executes immediately.
Conclusion
Callback functions are an essential concept in JavaScript. They help make code more flexible and are widely used in asynchronous programming and event handling.
Top comments (0)