Functional idioms — currying, composition, copies, lazy iterators, tags

javascript · folio

In one line: Functions are values: pass them, return them, let them close over state. Build behaviour from small functions over values you do not mutate: currying and partial application fix arguments, pipe chains steps, toSorted / with copy instead of mutating, iterator helpers pull one value at a time, and a tagged template is a function call on a template’s pieces.

Download PDF Print view LaTeX source

Functional idioms — currying, composition, copies, lazy iterators, tags — figure 1
Functional idioms — currying, composition, copies, lazy iterators, tags — figure 2

Currying, partial application, composition

  • Currying turns f(a, b, c) into f(a)(b)(c), one argument per call; an auto-curry (diagram 1) also takes several per step. Partial application fixes some and returns a function of the rest: f.bind(t, 10), (...r) => f(10, ...r).
  • bind also fixes this — ignored by arrows (lexical this) and by new (bound arguments are still prepended). The bound function has no prototype; instanceof uses the target’s.
  • pipe(f, g)(x) = g(f(x)): left to right, a reduce. compose(f, g)(x) = f(g(x)): right to left (maths order), a reduceRight. Steps take one value: curry first.
  • |> pipeline operator — Stage 2, Hack style: the right side is any expression with a topic placeholder, x |> f(%) |> g(%, 1); the % token is not final. TC39 has rejected F# pipes (right side = a unary function) several times.
const curry = (fn, n = fn.length) => function curried(...args) {
  return args.length >= n ? fn.apply(this, args)
    : (...more) => curried.apply(this, [...args, ...more]); };
const sum3 = (a, b, c) => a + b + c;
curry(sum3)(1)(2)(3); curry(sum3)(1, 2)(3);       // 6, 6
const pipe = (...fs) => x => fs.reduce((v, f) => f(v), x);
const compose = (...fs) => x => fs.reduceRight((v, f) => f(v), x);
const inc = x => x + 1, dbl = x => x * 2;
pipe(inc, dbl)(3); compose(inc, dbl)(3);          // 8, 7
Array.from({ length: 4 }, (_, i) => i * i);       // [0, 1, 4, 9]

Array methods — what comes back

methodreturnsedge cases
map(f)array, same lengthholes stay holes; f is not called on them
filter(p)arraykeeps references, does not copy items
flatMap(f)arraymap + flat(1); a non-array stays one item
reduce(f, init)any valueno init: starts at index 1, [] → TypeError, one item → returned, f never called
find, findLastitemundefined if none — ambiguous if stored
findIndex, findLastIndexindex-1 if none
some, everybooleanstop at the first decisive item; [] → false, true
forEach(f)undefinedno break short of a throw
Object.groupBynull-proto objectkeys coerced to string or symbol
Map.groupByMapany value as key

groupBy is static because Array.prototype.groupBy broke sites that load the Sugar library (versions until 1.4.0 patched it), and .group broke code using arrays as hash maps.

Copy, don’t mutate

mutates · returnscopies · returns the new array
sort(cmp) · the same arraytoSorted(cmp)
reverse() · the same arraytoReversed()
splice(i, n, ...x) · the removed itemstoSpliced(i, n, ...x)
a[i] = v · vwith(i, v) — RangeError if out of range
push(x), unshift(x) · new length[...a, x], [x, ...a]
pop(), shift() · the removed itema.slice(0, -1), a.slice(1)

  • Copies are shallow and dense: holes become undefined ([3, , 1].toSorted() → [1, 3, undefined]); with counts a negative index from the end. TypedArrays get toSorted, toReversed, with — no toSpliced.
  • Objects: {...o, k: v} copies one level. Object.freeze(o) returns the same o and is shallow — nested objects stay writable; writing a frozen property throws TypeError in strict code and is silently dropped in sloppy code.
  • Records & Tuples (deeply immutable, compared by value) were withdrawn at Stage 2 on 14 Apr 2025: no consensus for new primitives. The successor, Composites, makes objects, not primitives — early stage.

Lazy: generators + iterator helpers

  • Calling a function* runs nothing: it returns a generator; each next() runs to the next yield and parks the frame — only that frame is kept, so a sequence can be infinite.
  • Generators and the array, Map, Set and string iterators inherit Iterator.prototype, so helpers chain directly; an array needs .values(); any iterable or next() object → Iterator.from(x).
  • Lazy, return an iterator: map filter flatMap take drop. Consuming: reduce toArray forEach some every find. Iterator flatMap must get an iterator or iterable back — a string throws TypeError; take, drop: RangeError for a negative or NaN count.
  • Single pass, no fork: helpers share their source, and a consumed iterator just yields nothing — no error. break or a throw in for…of calls return(): the generator runs its finally and is finished for good.
function* naturals() { let n = 1; while (true) yield n++; }
naturals().map(n => n * n).filter(n => n % 2 === 0)
  .take(3).toArray();            // [4, 16, 36] - map ran 6 times
Iterator.concat([1, 2], new Set([3])).toArray();      // [1, 2, 3]
Iterator.zip([[1, 2, 3], ['a', 'b']]).toArray();
  // [[1, 'a'], [2, 'b']]  shortest by default; 'longest', 'strict'
Object.groupBy([1, 2, 3, 4], n => n % 2 ? 'odd' : 'even');
  // { odd: [1, 3], even: [2, 4] }   null prototype
const memo = f => { const cache = new Map();   // f(x) once per x
  return x => cache.getOrInsertComputed(x, f); };
const sql = (strs, ...vals) => ({
  text: strs.reduce((q, s, i) => q + '$' + i + s), values: vals });
sql`SELECT * FROM t WHERE id = ${7}`;
  // { text: 'SELECT * FROM t WHERE id = $1', values: [7] }

Tags, IIFE, arguments, code from strings

  • A tagged template may hold invalid escapes (\unicode): cooked undefined, raw kept; untagged it is a SyntaxError. String.raw`Hi\n${2 + 3}!` → Hi\n5! (6 characters). A tag may return anything — a function, a query object; an html tag must escape the values, an sql tag sends them as parameters.
  • IIFE (function () { … })(), (() => { … })(): the parentheses make it an expression — a private scope run once; each module now has its own. Modules have top-level await: an async IIFE is for CommonJS and classic scripts.
  • arguments: array-like (no map), absent in arrows. In sloppy code with only simple parameters it is aliased: arguments[0] = 99 changes a; strict code or default / rest / destructured parameters break the link. ...rest is a real array.
  • Direct eval(s) sees the local scope; indirect (0, eval)(s), eval?.(s) and new Function('a', 'return a + 1') see only globals. node:vm: “not a security mechanism. Do not use it to run untrusted code.”

Traps

  • ['1', '2', '3'].map(parseInt) → [1, NaN, NaN]: the index becomes the radix (parseInt('2', 1)). Use map(Number).
  • [10, 9, 1].sort() → [1, 10, 9]: compared as strings — and the array itself is reordered. toSorted((a, b) => a - b).
  • xs.forEach(async x => …) returns before any await settles: use for…of + await, or Promise.all(xs.map(f)).
  • A line starting with (, [ or ` continues the previous one: const a = b + newline + (() => {})() is b(() => {})(). Start such a line with ;.

Remember

Curry: one argument per call · partial: some now · pipe: left to right · copy: toSorted, with · iterators: lazy, one pass · tag: a call on the pieces.

Report a problem ·Discuss this folio