The Callback functions are an important part of JavaScript. They are mostly used to run a function in response to the completion of a synchronous or asynchronous task. In this tutorial, we will learn what is a callback function, how to create one, the need for it and some of its use cases using examples
Table of Contents
What is a Callback Function
JavaScript Callback function is a function that is passed as an argument to another function. Another function usually invokes the function when it finishes some task or completes some event.
How to create a Callback Function
In JavaScript, functions are special objects. We learned about JavaScript functions and about how to pass arguments to a JavaScript Function. The following code creates a function using function declaration.
1 2 3 4 5 | function sayHi() { console.log("Hi"); } |
Here sayHi
is not only the name of the function but also a variable that stores the function. We invoke the function by passing arguments inside the parenthesis after the variable name. Since sayHi does not have any parameters, an empty parenthesis will suffice.
1 2 3 4 5 | //sayHi is the function variable sayHi() //invoke it by using the empty parenthesis |
Since functions are objects we can assign it another a variable. And then use that variable to invoke the function.
1 2 3 4 | f=sayHi //f is also points to sayHi function f() //invoke the function |
This feature gives us the ability to pass a function as an argument to another function.
In the following code sayHi
& welcome
are regular JavaScript functions. The welcome
function declares function as its parameter (f
). It invokes the function by using the f()
.
We pass sayHi
as the argument to the welcome function. The welcome function invokes the sayHi
and displays the hi
message.
In this example, sayHi
is our callback function, because it is passed to welcome and invoked by it.
1 2 3 4 5 6 7 8 9 10 11 12 | function sayHi() { console.log("Hi"); } function welCome(f) { f(); } welCome(sayHi) |
Note that, the following example, does the same thing, but it is not callback. Because in this case sayHi is fixed and cannot be changed.
The function is callback function only if we pass it in the argument of the function.
1 2 3 4 5 6 7 8 9 10 11 12 | function sayHi() { console.log("Hi"); } function welCome() { sayHi(); } welCome() |
Need for Callback
The callback functions are many use cases. It is very useful in asynchronous actions. The asynchronous actions are those actions where JavaScript needs to wait for the action to complete.
For Example, waiting for the user to click on the button. We do not know when the user will click on the button. So we pass a callback function to the buttons click event. Whenever the user clicks the callback function is executed and we can respond to that.
CallBack Function Example
The following is one of the simple examples of callback.
We want our addNum
to either print the result to console or show it an alert window based on some condition.
We create two functions. logToConsole
prints the message to the console window, while logToAlert
uses the alert
window to display the message.
The addNum
function takes the callback function as the third parameter. It invokes the callback function passing the result of addition as the argument. It does not care how the results are displayed.
We choose between logToConsole
and logToAlert
based on the value of someCond
. If someCond
is 1 then use the logToConsole
else use the logToAlert
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function logToConsole(message) { console.log(message) } function logToAlert(message) { alert(message) } function addNum(a, b, callBack) { let result = a + b callBack(result) return result; } let someCond = 1 let f; if (i == 1) { f = logToConsole } else { f = logToAlert } addNum(1, 2, f) |
This is one of the simple use cases for callback functions.
Here is another example of callback function. The operate operates on two numbers using the given callback function. You can pass addNum
or multiplyNum
to it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function addNum(a, b) { return a + b } function multiplyNum(a, b) { return a * b } function operate(func, a, b) { return func(a, b) } let result = operate(addNum, 10, 10) console.log(result); //20 let result = operate(multiplyNum, 10, 10) console.log(result); //100 |
Callback to Array map method
The map() method of the array creates a new array after running the function on each element of the array.
In the example below, we multiply each element by 2 to create a new array in a callback function. The method below uses the arrow function as callback
1 2 3 4 5 6 7 8 9 10 11 | const numbers = [2, 4, 6, 8]; const doubled = numbers.map( (number) => { return number * 2; } ); console.log(doubled); // => [4, 8, 12, 16] |
The above example using regular function.
1 2 3 4 5 6 7 8 9 10 11 | const numbers = [2, 4, 6, 8]; const doubled = numbers.map(multiply); function multiply(n) { return n*2 } console.log(doubled); // => [4, 8, 12, 16] |
Asynchronous JavaScript
Responding to Asynchronous events is one of the important use cases for the callback functions.
In the following example, we use the setTimeout
to mimic a Asynchronous event. The setTimeout has two parameters. a callback function and a time. It executes the callback function after the a specified time is passed.
In this example, it executes the sayHi
callback function after a delay of 3000 ms.
1 2 3 4 5 6 7 8 9 | setTimeout(sayHi, 3000); function sayHi() { console.log("Hi") } |
CallBack Function Use cases
Callback functions are useful when you want to run a function in response to some event. Handling the browser event or responding to an HTTP request are the most common use cases.
Handling Browser Events
Web applications need to respond to events like button clicks, mouse movements, keyboard events, etc. We attach event handlers to respond to those events. These event handlers are nothing but callbacks
In the following example, we attach a function expression to the click
event of the button
element using the addEventListener
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!doctype html> <html> <head> <title> Functions as callbacks </title> <meta charset="utf-8"> </head> <body> <button id="buttonRef">Click Me</button> </body> <script> let buttonRef = document.getElementById("buttonRef") buttonRef.addEventListener("click", clicked, false); function clicked() { alert("You clicked Me") } </script> |
Alternatively, we can pass the Anonymous function directly, without declaring it
1 2 3 4 5 6 7 8 | <script> let buttonRef = document.getElementById("buttonRef") buttonRef.addEventListener("click", function () { alert("You Clicked Me"); }, false); </script> |
Responding to HTTP Requests
Sending HTTP Requests is another example of using callbacks. Here we use the fetch
api to send the HTTP request. fetch API returns a promise, which is handled by the first callback. It converts it into a JSON and returns another promise. The second callback then displays the result in the console. If the fetch API errors out, it is handled by another callback in the catch method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <!doctype html> <html> <head> <title> Functions as callbacks </title> <meta charset="utf-8"> </head> <body> </body> <script> fetch("https://api.github.com/users/tektutorialshub/repos") .then( //call back function function (response) { return response.json(); } ) .then( //call back function function (data) { console.log(data); } ) .catch( //call back function function (error) { console.log("Error: " + error); } ); </script> |