Higher Order Functions
In JavaScript, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions. A Higher-Order Function (HOF) is a function that does at least one of the following:
- Takes one or more functions as arguments (callbacks).
- Returns a function as its result.
Higher-Order Functions form the backbone of functional programming in JavaScript.
1. Array Built-in Higher-Order Functions
JavaScript's Array.prototype includes several powerful HOFs that allow you to operate on arrays efficiently and declaratively.
Array.prototype.map()
Transforms every element in an array and returns a new array of the exact same length.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
// doubled: [2, 4, 6]
Array.prototype.filter()
Returns a new array containing only the elements that pass the condition specified in the callback.
const ages = [15, 22, 18, 12, 30];
const adults = ages.filter(age => age >= 18);
// adults: [22, 18, 30]
Array.prototype.reduce()
Executes a reducer function on each element, resulting in a single output value. Essential for aggregations or complex transformations.
const prices = [10, 20, 30];
const total = prices.reduce((sum, currentPrice) => sum + currentPrice, 0);
// total: 60
Array.prototype.forEach()
Executes a provided function once for each array element. Unlike map, it returns undefined and is used primarily for side effects (like logging or DOM updates).
const fruits = ['apple', 'banana'];
fruits.forEach(fruit => console.log(fruit));
Finding and Checking Elements
find(): Returns the first element that satisfies the provided testing function.some(): Returnstrueif at least one element passes the test.every(): Returnstrueif all elements pass the test.
const users = [
{ name: 'Alice', admin: true },
{ name: 'Bob', admin: false }
];
const admin = users.find(u => u.admin); // { name: 'Alice', admin: true }
const hasAdmins = users.some(u => u.admin); // true
const allAdmins = users.every(u => u.admin); // false
Array.prototype.flatMap()
Maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1.
const phrases = ["hello world", "how are you"];
const words = phrases.flatMap(phrase => phrase.split(" "));
// words: ["hello", "world", "how", "are", "you"]
2. Creating Custom Higher-Order Functions
You can easily create your own HOFs. A common use case is creating functional wrappers like withLogging or throttle/debounce.
// A function that returns another function
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Summary
Embracing Higher-Order Functions encourages declarative code. Rather than writing imperative for loops where you manually manage state and counters, HOFs like .map() and .reduce() allow you to describe what you want to achieve, abstracting away the how.