What is the definition of a higher-order function in JavaScript?

Answer

A higher-order function in JavaScript is a function that either:

  1. Takes one or more functions as arguments (callbacks), or
  2. Returns a function as its result.

Higher-order functions allow for more dynamic and reusable code by enabling functional programming patterns.

Examples of Higher-Order Functions

Skopiuj kod
function repeatOperation(operation, times) {
  for (let i = 0; i < times; i++) {
    operation();
  }
}

repeatOperation(() => console.log("Hello"), 3);
// Output: Hello (3 times)
Skopiuj kod
function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}

const double = multiplier(2);
console.log(double(5)); // 10
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]

Why Use Higher-Order Functions?

MDN Web Docs: Closures