What is the definition of a higher-order function?

MediumIntermediateJavascript
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

A higher-order function is a function that either takes another function as an argument, returns a function, or does both. It treats functions as values, enabling powerful patterns like callbacks, closures, and function composition.

Answer

The Core Idea

In JavaScript, a higher-order function is any function that either:

  • Takes one or more functions as arguments, or
  • Returns another function as its result.

In other words, it treats functions as values — passing them around just like variables.

Feature

Description

Example

Accepts functions as arguments

A function receives another function and calls it inside.

setTimeout(() => console.log('Hi!'), 1000)

Returns a function

A function produces another function when called.

function multiplier(x) { return y => x * y }

The two main ways a function can be considered higher-order.

Example 1: Taking a Function as an Argument

Functions like map, filter, and forEach are classic examples — they take another function and apply it to elements of an array.

JAVASCRIPT
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
                  

Example 2: Returning a Function

A function can return another function that 'remembers' the outer scope — this is often used in currying or closures.

JAVASCRIPT
function greet(message) {
  return function(name) {
    console.log(`${message}, ${name}!`);
  };
}

const sayHello = greet('Hello');
sayHello('Alice'); // Hello, Alice!
                  

Why It Matters

Higher-order functions are the foundation of modern JavaScript patterns like:

  • Callbacks (e.g., event handlers)
  • Promises and async/await
  • Functional utilities like map, reduce, filter
  • Middleware and decorators in frameworks like Express or Redux.
Still so complicated?

Think of a higher-order function like a chef that doesn’t cook food directly — it takes other chefs (functions) and tells them how to cook. The chef can even create a new chef recipe on the spot and hand it back to you!

Summary

A higher-order function:

  • Takes one or more functions as parameters or returns a function.
  • Enables reusability and abstraction in code.
  • Is a key building block of functional programming in JavaScript.
Similar questions
Guides
24 / 61