Learn How to Pass a Function as a Parameter in JavaScript


In JavaScript, you can pass a function as a parameter to another function by simply passing the function name without invoking it with parentheses.

Here's an example of how to pass a function as a parameter in JavaScript:

// Define a function that takes another function as a parameter
function performOperation(operation, a, b) {
  return operation(a, b);

// Define the functions that will be passed as parameters
function add(a, b) {
  return a + b;

function subtract(a, b) {
  return a - b;

// Call the performOperation function with different operations
console.log(performOperation(add, 5, 3)); // Output: 8
console.log(performOperation(subtract, 5, 3)); // Output: 2

In the above example, we define a performOperation function that takes three parameters: operation, a, and b. The operation parameter is the function we want to perform on a and b. We then define two functions, add and subtract, that will be passed as the operation parameter to the performOperation function. Finally, we call the performOperation function twice, passing in different functions each time, and log the results to the console.