Hiprup

What is a higher-order function?

A higher-order function is a function that takes another function as an argument, returns a function, or both.

  • Takes a function — array methods like map, filter and reduce accept a callback.

  • Returns a function — used for function factories and currying.

Why it matters: higher-order functions make code reusable and declarative, and are a foundation of functional programming.

// Takes a function as argument
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);   // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15

// Returns a function
function createGreeter(greeting) {
  return function(name) {  // Returns a function
    return `${greeting}, ${name}!`;
  };
}
const hello = createGreeter('Hello');
const hi = createGreeter('Hi');
console.log(hello('John')); // 'Hello, John!'
console.log(hi('Jane'));    // 'Hi, Jane!'

// Both: takes and returns a function (decorator)
function withLogging(fn) {
  return function(...args) {
    console.log(`Calling ${fn.name} with`, args);
    const result = fn(...args);
    console.log(`Result:`, result);
    return result;
  };
}

const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(3, 4); // Logs: 'Calling add with [3, 4]', 'Result: 7'

filter takes a predicate function and returns filtered elements. createGreeter takes a greeting and returns a customized function. withLogging takes a function and returns a wrapped version with logging. These are all higher-order functions — they treat functions as values.

Name built-in examples (map, filter, reduce, forEach, sort). Show a custom higher-order function (factory or decorator).

The decorator pattern (withLogging) shows practical application. Functions as first-class citizens is the underlying concept.

What is a higher-order function? | Hiprup