JavaScript allows you to pass multiple parameters to a function which will be used as a callback.
A callback function is basically a function which you can pass to another function, and call it at some point in time. The main benefit of using a callback function is that you can do some additional computing before calling the callback function. Here I’m going to show you two examples on how that works. One with defined parameters in the function, and one without parameters. Note that both the callers will have parameters defined.
function addNumbers (param1, param2) {
console.log(`Sum = ${param1 + param2}`);
}
function useCallbackForNumbers(callback) {
console.log(`Numbers are ${arguments[1]} and ${arguments[2]}`);
callback(arguments[1], arguments[2]);
}
useCallbackForNumbers(addNumbers, 4, 5);
Code language: JavaScript (javascript)
In the above example, I’ve called a function named useCallbackForNumbers, inside which I’m passing three arguments. A callback function named addNumbers to add the numbers, a number (4) and another number (5). Now I want to show what the entered numbers were before summing them up. You’d notice that on line 6 I’ve shown what the numbers where to the console. I’ve then called the callback function to sum the numbers. I’ve used the JavaScript object keyword arguments to access the second and the third parameter. You can also use defined parameters if you want as below:
function useCallbackForNumbers(callback, numberOne, numberTwo) {
console.log(`Numbers are ${numberOne} and ${numberTwo}`);
callback(numberOne, numberTwo);
}
Code language: JavaScript (javascript)
In both the cases, you should see the following output: