Higher-Order Functions

Difficulty: Intermediate

Question

What are higher-order functions in JavaScript? Give practical examples.

Answer

A higher-order function is a function that does at least one of the following:

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

Higher-order functions are a core concept in functional programming and are used extensively in JavaScript. Built-in examples include Array.prototype.map, filter, reduce, forEach, sort, and setTimeout.

Code examples

Functions as Arguments

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
console.log(doubled);

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);

const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum);

// Custom higher-order function
function repeat(n, action) {
  for (let i = 0; i < n; i++) action(i);
}
repeat(3, i => console.log(`Iteration ${i}`));

map, filter, reduce all accept a function as an argument. repeat is a custom HOF.

Functions Returning Functions

// Multiplier factory
function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}

const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5));  // 10
console.log(triple(5));  // 15

// Logger with prefix
function createLogger(prefix) {
  return (message) => console.log(`[${prefix}] ${message}`);
}

const info = createLogger("INFO");
const error = createLogger("ERROR");
info("Server started");
error("Connection failed");

These are function factories - functions that create and return specialized functions.

Key points

Concepts covered

Higher-Order Functions, Callbacks, Functional Programming, Abstraction