In simple language Callback functions are just functions that take another function as it’s argument. That’s it.
Let’s take a small example to better demonstrate what I am talking about.
function calc(add){
let a = add + 3;
console.log(a);
}
const add = (a,b) => {
let sum = a + b;
return sum;
}
calc(add(2,4));
Here I have two functions
calc and add
Let’s first talk about add.
The add function adds two values and returns the value.
The calc function takes an argument and whatever the argument returns, it adds 3 to it.
The add function over here is the callback function. We are calling add here as a parameter inside another function. This fits the the definition of callback functions.
We can also pass anonymous functions as callback functions.
function sayHello(hi){
console.log('Hello');
hi();
}
sayHello(function(){
console.log('hi')
})
Output:
hello
hi
sayHello passes an anonymous function.
We use callbacks often without even knowing it. Consider the setTimeout function.
setTimeout uses the callback function like so
setTimeout(() => {console.log('Inside a callback')},3000);
// logs 'Inside a callback' after 3 seconds
Here setTimeout prints ‘Inside a callback’. This too was a callback function that too an anonymous one.
Imagine if callback didn’t exists. We wouldn’t be able to make asynchronous behavior without it.
Top comments (0)