while learning javascript, I came across a concept called a callback funtion.
At first, the name sounds complicated. But the idea is actually pretty simple.
What is a callback function?
A callback function is a function passed into another function as an argument, which can be called later.
for example:
function greet(name) {
console.log("Hello " + name);
}
function processUser(callback) {
callback("Alex");
}
processUser(greet);
Here, greet is passed to processUser as an argument.
Inside processUser, we call:
callback("Alex");
So greet() gets executed.
Why do we use Callbacks?
Callbacks are useful when we want one function to run another function after something happens.
or example:
function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(10, 20, function(result) {
console.log(result);
});
Output:
30
The callback receives the result after the calculation is completed.
Callbacks are especially important in JavaScript because they are commonly used with events, timers, and asynchronous operations.
Simple way to remember
Function → Does the work
Callback → Function passed to another function
callback() → Executes the passed function
Top comments (0)