Callback Functions
An anonymous function can be assigned to a variable.
And hence, like any data assigned to a variable, a function can also be passed as an argument to other functions. Such a function is known as a callback function.
Below we give an example of a function called irrational()
that accepts a function as its parameter, and executes it
function irrational(f) {
console.log(f());
}
We declare another function called pi()
that returns the value of π
function pi() {
return Math.PI;
}
and pass it as an argument to irrational()
irrational(pi);
The function irrational()
executes it and prints the value 3.141592653589793
in the console. Here, pi()
is a callback function.
Anonymous Callback Functions
Instead of declaring pi()
separately, we can pass it as an anonymous function as shown below
irrational(function(){
return Math.PI;
});
That nameless passed function is known as an anonymous callback function.