How to create and use higher-order functions in JavaScript
· Category: JavaScript
Short answer
Higher-order functions accept other functions as arguments or return functions, enabling abstraction over behavior, callbacks, and functional composition.
Steps
- Accept a function as a callback:
javascript function mapArray(arr, transform) { const result = []; for (const item of arr) result.push(transform(item)); return result; } console.log(mapArray([1, 2, 3], x => x * 2)); // [2, 4, 6] - Return a function to create specialized behavior:
javascript function greaterThan(n) { return m => m > n; } const greaterThan10 = greaterThan(10); console.log(greaterThan10(11)); // true - Compose functions for reusable pipelines:
javascript const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const add1 = x => x + 1; const double = x => x * 2; console.log(compose(double, add1)(3)); // 8
Tips
- Higher-order functions reduce repetition by abstracting control flow.
- Keep returned functions pure when possible for easier testing.
Common issues
- Over-nesting higher-order functions can hurt readability; name intermediate steps.
- Forgetting to handle
thiscontext when passing methods as callbacks.