Higher-order Functions

Expert-Level Explanation

Higher-order functions in JavaScript are functions that can take other functions as arguments or return them as results. This concept is a direct result of JavaScript treating functions as first-class citizens.

Creative Explanation

Think of a higher-order function as a talent show judge. The judge can invite contestants (functions) to perform (passed as arguments) and can also recommend new talents (return functions).

Practical Explanation with Code

// Higher-order function taking another function as an argument
function repeat(times, fn) {
  for (let i = 0; i < times; i++) {
    fn(); // calling passed function
  }
}

repeat(3, function() { console.log("Hello!"); });

// Higher-order function returning a function
function greaterThan(n) {
  return function(m) {
    return m > n;
  };
}

const greaterThan10 = greaterThan(10);
console.log(greaterThan10(11)); // true

Real-world Example

A higher-order function is like a factory manager who oversees several machines (functions). The manager might adjust these machines to perform specific tasks (pass functions as arguments) or create new machines for specialised tasks (return new functions).