What is a higher order function?

JavaScriptPayPal

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

function higherOrderFunction(fn) {
fn();
}

Real world examples

// Example 1: map() is a higher-order function because
// it takes a function as an argument
numbers.map(num => num * 2)
// ^^^^^^^^^^^^ This is the function being passed as an argument

// Example 2: filter() is a higher-order function because
// it takes a function as an argument
const isEven = num => num % 2 === 0;
numbers.filter(isEven)
// ^^^^^^ This function is passed as an argument

// Example 3: reduce() is a higher-order function because
// it takes a function as an argument
numbers.reduce((total, current) => total + current, 0)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This function is passed as an argument

// Example 4: multiplier() is a higher-order function because
// it returns a function
function multiplier(factor) {
return number => number * factor; // <- Returns a function
}

// Example 5: compose() is a higher-order function because it:
// 1. Takes two functions as arguments (f and g)
// 2. Returns a new function
const compose = (f, g) => x => f(g(x));

// Example 6: debounce() is a higher-order function because it:
// 1. Takes a function as an argument (func)
// 2. Returns a new function
function debounce(func, delay) {
return function(...args) { ... } // <- Returns a function
}
00:00