You can pass a callback function to another function to use it later. But, you can also pass multiple functions as callback functions to another function. For example, let’s say you have two numbers n1 and n2. And you want to square the sum of those two numbers, i.e., (n1+n2)^2. In such cases, you can pass two functions, one to sum the numbers and another to square the result of the sum. You can use the first function to create the intermediate result, required for the second function. Here’s how you can do it:
function squareNumbers(number) {
console.log(`Squared number = ${number * number}`)
}
function addNumbers(number1, number2) {
return number1 + number2
}
function useCallbackForNumbers(callbackAdd, callbackSquare) {
const sumOfNumbers = callbackAdd(arguments[2], arguments[3])
callbackSquare(sumOfNumbers)
}
useCallbackForNumbers(addNumbers, squareNumbers, 2, 3)
Code language: JavaScript (javascript)
In line number 10, I’ve used the first callback function called callbackAdd (which originally references to addNumbers method). Then on line number 11, I’ve used the result of the function to get the square of the number using callbackSquare (which originally references to squareNumbers). The result you get should be 25. (2+3)^2 = 5^2 = 25.
Output should look like: