Higher-order functions — functions that take and return functions¶
Level: 101 · for anyone who has passed a function to map or sort
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A function that takes a callback decides what arguments the callback gets: ["1", "2", "3"].map(parseInt) is [1, NaN, NaN] because map also passes each index, which parseInt reads as a radix — and tsc accepts the call without a word.
Keywords: higher-order function
What the finished page will answer¶
- What does
["1", "2", "3"].map(parseInt)return, which three arguments doesmappass on each call, and how domap((s) => parseInt(s, 10))andmap(Number)fix it? - Why does
tsc --strictacceptmap(parseInt): how doesparseInt's optionalradixline up withmap'sindex? - How do you write a function that returns a function (
twice,once,memoize), and what does each keep between calls? - In what order do
compose(f, g)andpipe(f, g)run their functions, and what does each return forx = 1?
Examples it will need¶
-
higher_order_map_parseint_js.js— map(parseInt) beside the three fixes, with the arguments map passes logged on each call -
higher_order_returning_functions_js.js— twice, once, memoize, compose and pipe built from closures, with a counter showing which calls ran the wrapped function -
higher_order_parseint_typechecks_ts.ts— the same map(parseInt) call, which passes tsc --strict and still prints [ 1, NaN, NaN ]
See also¶
map,filter,reduceand friends — the higher-order methods every array already has- Closures — why a returned function still sees its maker's variables
- Parsing numbers — what parseInt does with the radix map hands it
- Callbacks — functions passed now and called later
- Rust: Iterators are lazy ↗ — how Rust's map differs: a lazy adapter, where an array's map runs at once
- Concurrency: Where does a callback keep its state? ↗ — where a callback keeps the state it needs, across languages