Callback Function in JavaScript
In this javascript callback function tutorial, we will learn about what are callback functions, how you can use them including synchronous and asynchronous callbacks.
- What is a callback function?
- javascript map callback function
- Anonymous callback function
- Types of callback function
Table Of Contents
What is a callback function in javascript?
A callback function is nothing but a simple function in JavaScript that can be passed as an argument in another function and can be invoked inside this outer function.
The callback function is a must-know for JavaScript developers, it is used in arrays, events handlers, timer functions, and mainly to make asynchronous calls in JavaScript.
How to create a callback function?
Creating a callback function is simple just create a normal function and pass the reference of the function in another function as an argument.
Possible mistake: pass just the name of the function and don't use parenthesis with it.
Right: calculate(a, b, sum);
Wrong: calculate(a, b, sum());
Let's create a calculate function that accepts a callback function and on the basis of that callback function it will add or subtract numbers.
function calculate(num1, num2, callbackFunction) {
callbackFunction(num1, num2); // calling cal;back function
}
function add(a, b) {
console.log(a + b);
}
function subtract(a, b) {
console.log(a - b);
}
calculate(5, 3, add); // add is a callback function here
calculate(5, 3, subtract); // subtract is a callback function here
Try It
In the above example, the calculate function takes sum as an argument which becomes a callback function here and then calls it inside the calculate function, and the same happens for subtract function.
Note: Both regular function and arrow function can be served as a callback function.
JavaScript map callback function in an array
There are many array methods that use callback functions to perform some task for individual elements of array-like in map, filter, find, etc.
Let's take an array of some user's name and you have to greet them all using a greet function. How will you do it?
One method is to call the greet function for each element using for loop, or you can use the map
method and pass the greet function as a callback in it.
The map
method will itself call the greet function for each and every element of the array.
let users = ["John", "Herry", "Annie"];
function greet(user) {
console.log("Hello " + user + "!");
}
users.map(greet); // passing greet as a callback function
Try It
Note: The function that accepts another function as an argument are known as a higher order function, i.e. calculate and map method used above are higher order function.
One important thing to look out for is that it is the responsibility of higher order function to invoke the callback function and provide it with the right argument.
Look at the above examples, the higher order function calculate() and user.map() invokes the callback function with the right argument.
The user.map() function pass elements of the array and also calls it.
Anonymous Callback Function
It is not necessary to create a function then pass it to the higher order function, you can directly create an anonymous function replacing the argument position.
Here is an example of an anonymous callback function.
let users = ["John", "Herry", "Annie"];
users.map(function (user) {
console.log("Hello " + user + "!")
}); // passing anonymous function as callback
Try It
In the above example, we passed an anonymous function that takes an individual element as an argument and performs a specified task over it.
You can also use the arrow function at this place.
let users = ["John", "Herry", "Annie"];
users.map(user => console.log("Hello " + user + "!"));
Try It
Types of callback function
The callback function can be executed in both synchronous and asynchronous ways.
Synchronous callback function
The callback function is used in asynchronous programming but all callback function does not execute in a synchronous way. A block of code that executes one by one is synchronous.
Here is an example of a synchronous callback function.
function calculate(num1, num2, callbackFunction) {
console.log("calculation started");
callbackFunction(num1, num2);
console.log("calculation finished");
}
function add(a, b) {
console.log(a + b);
}
calculate(5, 3, add);
// calculation started
// 8
// calculation finished
You can see by running the above example, Synchronous callbacks are blocking. This means the higher order function finishes its execution only after callbacks have finished its execution.
Order of execution:
- Higher order function starts execution.
- Callback function executes
- Higher order function finishes execution.
Asynchronous callback function
The asynchronous callback functions are non-blocking means the higher order function does not wait for the execution of the callback function but it make sure of the execution of the callback function on a certain event.
JavaScript does not wait for an operation to complete in asynchronous programming but it will execute the rest of the code while waiting for some result.
When the result arrives then it executes a callback function which is asynchronous callback function.
function calculate(num1, num2, callbackFunction) {
console.log("calculation started");
setTimeout(() => callbackFunction(num1, num2), 1000);
console.log("calculation finished");
}
function add(a, b) {
console.log(a + b);
}
calculate(5, 3, add);