CodePark/ questions / Functional patterns
START PRACTICINGPRACTICE
Frontend question · JavaScript › Functional patterns

What is a higher-order function? Give examples.

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

This is possible because functions in JavaScript are first-class values. You can store them in variables, pass them around and return them, like any other value.

Examples that take a function:

  • Array.prototype.map, filter and reduce
  • sort with a compare function
  • setTimeout
  • addEventListener

Examples that return a function:

  • debounce, memoize and curry
  • Function.prototype.bind
  • factories like const multiplier = n => x => x * n

In React, higher-order components and custom hooks that return callbacks use the same idea.

Higher-order functions let you reuse behaviour, not just values. This removes duplicate code. For example, the looping logic lives inside map, and you only supply the part that changes.

  • A higher-order function takes a function as an argument, returns one, or both.
  • It works because functions are first-class values in JavaScript.
  • Built-in examples are map, filter, reduce, setTimeout and addEventListener.
  • Examples that return functions are bind, debounce, memoize and factories.