Higher-order operations and reusable behavior
Quick answer
A higher-order function accepts a function, returns one, or both. This separates common control flow from the behavior that changes between callers.
How it works
For a reusable transformation, accept a callback with a documented input and output contract. map invokes a callback with value, index and source array; a wrapper may intentionally forward only the value. Returning a function enables configuration once and reuse later. Callbacks can have side effects, so higher-order code is not automatically pure.
const twice=(fn,x)=>fn(fn(x)); console.log(twice(n=>n+3,4),twice(n=>n*2,4));Expected output in Node.js:
10 16The same higher-order operation reuses different behavior.
const scale=k=>n=>n*k;const triple=scale(3);console.log(JSON.stringify([2,4].map(triple)));Expected output in Node.js:
[6,12]Configuration returns a reusable function.
Common mistakes
Pass a callable, not the result of invoking it. Document which arguments are forwarded; extra callback arguments can change behavior.
Practice
Build a function that transforms each input twice with a provided callback. Compare two different callbacks.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Higher-order operations and reusable behavior — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Why pass a callback to a reusable higher-order transformation instead of duplicating its loop?
What does scale(3) return in a factory written k => n => n*k?
Is every higher-order function pure?
What is the exact console output in Higher-order operations and reusable behavior example 1?
const twice=(fn,x)=>fn(fn(x)); console.log(twice(n=>n+3,4),twice(n=>n*2,4));What is the exact console output in Higher-order operations and reusable behavior example 2?
const scale=k=>n=>n*k;const triple=scale(3);console.log(JSON.stringify([2,4].map(triple)));