Skip to main content

Higher-order function

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


Detailed explanation

In JavaScript, functions are first-class citizens, which means they can be:

  • passed as values,
  • stored in variables,
  • returned from other functions.

Functions that use other functions this way are called higher-order.


Code examples

1. Takes a function as an argument

javascript
function repeat(n, action) { for (let i = 0; i < n; i++) { action(i); } } repeat(3, console.log); // 0 // 1 // 2

repeat is a higher-order function because it calls the passed-in action function.


2. Returns a new function

javascript
function multiplier(factor) { return function (num) { return num * factor; }; } const double = multiplier(2); console.log(double(5)); // 10

multiplier is a higher-order function because it returns another function.


3. Built-in examples in JS

Many array methods are higher-order functions:

javascript
[1, 2, 3].map(x => x * 2); // takes a function [1, 2, 3].filter(x => x > 1); // takes a function [1, 2, 3].reduce((a, b) => a + b, 0); // takes a function

Why they are needed

They increase flexibility and code reuse. They let you implement abstractions, for example handling collections, events, and so on. They are the core tool of functional programming.


Summary

PropertyDescription
What it doesTakes or returns functions
Examplesmap, filter, reduce, setTimeout, addEventListener
BenefitsLogic reuse, more compact code
Key ideaFunctions are data, just like numbers or strings

In one phrase:

A higher-order function is a function that treats other functions as data, taking them as arguments or returning them as a result.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.