Skip to content

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 does map pass on each call, and how do map((s) => parseInt(s, 10)) and map(Number) fix it?
  • Why does tsc --strict accept map(parseInt): how does parseInt's optional radix line up with map's index?
  • 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) and pipe(f, g) run their functions, and what does each return for x = 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

Sources to start from