Callback functions are a great way to pass around functionalities through the JavaScript code. One of the most powerful features of passing function to another function is that you can even pass the caller function to the called function (somewhat like a recursion). Let’s say, I want to create a functionality where I want to increment a number starting from 0, first by adding 1 and then by adding 5, again by 1 and then by 5. So that the series would look like 0, 1, 6, 7, 12, 13, 18…until I reach up-to 50. This can be easily done using callback functions calling each other. Here I’ve written a code to demonstrate the same:
let testNumber = 0
function addOne(callbackOne, callbackTwo) {
testNumber++
if (testNumber > 50) {
return
}
console.log('Add one:', testNumber)
callbackTwo(callbackOne, callbackTwo)
}
function addFive(callbackOne, callbackTwo) {
testNumber += 5
if (testNumber > 50) {
return
}
console.log('Added five:', testNumber)
callbackOne(callbackOne, callbackTwo)
}
function useCallbacksForNumbers(callbackOne, callbackTwo) {
callbackOne(callbackOne, callbackTwo)
}
useCallbacksForNumbers(addOne, addFive)
Code language: JavaScript (javascript)
In the above code, I’ve created two functions named addOne and addFive to add 1 and 5 respectively to the original number (0). You’d notice that I’ve then called a function named useCallbacksForNumbers to pass callback function one (addOne) and callback function two (addFive) to the first callback function (addOne). The first callback function then calls the second one (addFive) and vice-versa. This happens until the number increments to 54. However, 54 won’t be displayed because it tests for false at testNumber >50 check inside the addFive function. So, the result you’d see is: