Functions As Values

JavaScript supports first-class and higher-order functions. This is just a formal way of saying that functions can be treated exactly like any other data type—such as numbers, strings, or booleans.

You can assign functions to variables, store them in arrays, and most importantly, pass them as arguments to other functions.

Passing Functions as Arguments

Let’s assume we have two simple mathematical functions:

function add(x, y) {
  return x + y;
}

function mul(x, y) {
  return x * y;
}

We can create a higher-order function that accepts another function as one of its arguments. In this case, the arithmetic parameter expects a function:

function aggregate(a, b, c, arithmetic) {
  // It calls the provided function to calculate the first result
  const firstResult = arithmetic(a, b);
  
  // Then uses it again for the final result
  const finalResult = arithmetic(firstResult, c);
  
  return finalResult;
}

When calling aggregate, we pass the add or mul function by name, without parentheses (because we aren’t executing them yet, we are just handing them over).

const sum = aggregate(2, 3, 4, add);
console.log(sum); // Output: 9

const product = aggregate(2, 3, 4, mul);
console.log(product); // Output: 24

Practical Example

This pattern is extremely common when you need to apply different formatting rules to text dynamically.

function reformat(message, formatter) {
  // Apply the formatter function three times
  let result = formatter(message);
  result = formatter(result);
  result = formatter(result);
  
  return "PREFIX: " + result;
}

function addPeriod(str) {
  return str + ".";
}

// Pass the message and the formatting logic
console.log(reformat("General Kenobi", addPeriod));
// Output: PREFIX: General Kenobi...