Higher-Order Functions
reduce
Example:
Higher-order functions (HOFs) are a cornerstone of functional programming. These functions either take other functions as arguments or return them as results, enabling flexible and modular code. In JavaScript, higher-order functions are everywhere—from array methods like map and filter to custom utilities that enhance functionality.
Higher-Order Functions
A higher-order function is a function that:
- 1Takes one or more functions as arguments.
- 2Returns a function as its output.
This concept unlocks powerful programming techniques, allowing you to compose and manipulate behaviors dynamically.
Examples of Higher-Order Functions
1. Built-in Array Methods
Array methods like map, filter, and reduce are classic examples of higher-order functions.
map
Example:
Applies a given function to each element in an array.
const numbers = [1, 2, 3, 4];
const squared = numbers.map((num) => num * num);
console.log(squared); // [1, 4, 9, 16]
filter
Example:
Returns a new array containing elements that satisfy a condition.
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
reduce
Example:
Reduces an array to a single value using a callback function.
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 10
Custom Higher-Order Functions
Let’s create a function that logs the execution time of any function:
function measureExecutionTime(fn) {
return function (...args) {
const start = Date.now();
const result = fn(...args);
const end = Date.now();
console.log(`Execution time: ${end - start}ms`);
return result;
};
}
const slowFunction = (num) => {
for (let i = 0; i < 1e6; i++) {} // Simulates a delay
return num * 2;
};
const timedFunction = measureExecutionTime(slowFunction);
console.log(timedFunction(5)); // Logs execution time, then 10
Why Use Higher-Order Functions?
- 1Reusability: Encapsulate common logic and apply it across different scenarios.
- 2Modularity: Break down complex operations into smaller, testable functions.
- 3Readability: Simplify code by abstracting repetitive patterns.
Building a Custom Utility
Create a makeMultiplier
higher-order function that generates functions to multiply numbers by a specific factor:
function makeMultiplier(multiplier) {
return function (num) {
return num * multiplier;
};
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Conclusion
Higher-order functions are essential for advanced techniques like function composition (covered in the next lesson) and currying (discussed in Chapter 5). They enable a declarative coding style that’s clean, concise, and powerful.