Curriculum Series

What is a higher order function?

What is a higher order function?

What is a higher order function?

JavaScript

What is a higher-order function?

A higher-order function is a function that takes one or more functions as arguments or returns a function as its result.

In JavaScript, functions are first-class objects, which means they can be passed around like any other value. This allows for powerful and flexible programming patterns, such as callbacks, closures, and function composition.

Higher-order functions are a key feature of functional programming, which emphasizes the use of pure functions, immutability, and composition over inheritance.

Examples

JAVASCRIPT
1function higherOrderFunction(fn) {
2 fn();
3}

Real world examples

JAVASCRIPT
1// Example 1: map() is a higher-order function because
2// it takes a function as an argument
3numbers.map(num => num * 2)
4// ^^^^^^^^^^^^ This is the function being passed as an argument
5
6// Example 2: filter() is a higher-order function because
7// it takes a function as an argument
8const isEven = num => num % 2 === 0;
9numbers.filter(isEven)
10// ^^^^^^ This function is passed as an argument
11
12// Example 3: reduce() is a higher-order function because
13// it takes a function as an argument
14numbers.reduce((total, current) => total + current, 0)
15// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This function is passed as an argument
16
17// Example 4: multiplier() is a higher-order function because
18// it returns a function
19function multiplier(factor) {
20 return number => number * factor; // <- Returns a function
21}
22
23// Example 5: compose() is a higher-order function because it:
24// 1. Takes two functions as arguments (f and g)
25// 2. Returns a new function
26const compose = (f, g) => x => f(g(x));
27
28// Example 6: debounce() is a higher-order function because it:
29// 1. Takes a function as an argument (func)
30// 2. Returns a new function
31function debounce(func, delay) {
32 return function(...args) { ... } // <- Returns a function
33}

Finished reading?

Mark this topic as solved to track your progress.