A higher-order function is a function that either:
It's one of functional programming's foundation.
Examples of higher-order function in JS:
//map() and reduce() let nums = [1, 2, 3, 4] let addOne = nums.map((i) => i+1) // [2,3,4,5] let combined = nums.reduce((res, cur) => res+=cur, 0) // 10
Imagine you're working with lists of numbers and need to perform different operations (e.g., doubling, squaring, or adding a constant). Instead of writing multiple similar loops, you can abstract the behavior with a higher-order function.
//normal version let numbers = [1, 2, 3, 4]; const squares = (nums) => { let result = []; for(let i of nums) { result.push(i*i); } return result; } const addThree = (nums) => { let result = []; for(let i of nums) { result.push(i+3); } return result; } squares(numbers) // [1,4,9,16] addThree(numbers) // [4,5,6,7]
//higher-order function version let numbers = [1, 2, 3, 4]; const applyAll = (func, nums) => { let result = []; for(let i of nums) { result.push(func(i)); } return result; } applyAll((i) => i*i, numbers) // [1,4,9,16] applyAll((i) => i+3, numbers) // [4,5,6,7]
With one generic higher-order functionapplyAll, you can handle multiple operations and avoid repetitive code.
By composing small functions, you can build more complex behavior. For example, if you want to first filter a list of numbers to only get even numbers, and then double them, then add all of them together, you can chain higher-order functions.
//you can chain filter -> map -> reduce let numbers = [1, 2, 3, 4]; let result = numbers .filter(i => i%2===0) .map(i => i*2) .reduce((res, cur) => res+=cur, 0); // 12
Each step (filtering, mapping, reducing) is handled by a higher-order function, making the process more modular, easier to maintain, and testable in isolation.
That's it! Thank you for reading this far. Till next time!
The above is the detailed content of What is higher-order function in Javascript. For more information, please follow other related articles on the PHP Chinese website!