Sub topic 12
Point-Free Style
This chapter assumes you have read the chapters on composition and currying. You should be able to read a pipe helper and a curry helper and know what they return. You also need to know that array callbacks such as the one passed to map receive more than one argument.
What "point-free" means
In point-free style, you define a function without naming its arguments. The term comes from mathematics, where the "points" are the values a function acts on. Point-free code names the steps of a transformation. It never names the data that flows through them.
Compare two definitions of the same function:
const toUpper = (s) => s.toUpperCase();
// Pointed: names the argument `words`
const shoutAllPointed = (words) => words.map((w) => toUpper(w));
// Point-free: passes toUpper directly, no `w`
const shoutAll = (words) => words.map(toUpper);
console.log(shoutAllPointed(['a', 'b'])); // [ 'A', 'B' ]
console.log(shoutAll(['a', 'b'])); // [ 'A', 'B' ]The second version is point-free in its callback. (w) => toUpper(w) is a wrapper that only forwards its argument, so you can drop it and pass toUpper itself. This step is called eta-reduction. It is the basic move in point-free code.
To make a whole function point-free, including its outer argument, you need curried, data-last helpers and a composition function.
Building point-free pipelines
A data-last helper takes its configuration first and the data last. When you curry it, you can supply the configuration now and get back a function that waits for the data. Composition then joins those waiting functions together.
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
// Data-last, curried helpers
const map = curry((fn, xs) => xs.map(fn));
const filter = curry((pred, xs) => xs.filter(pred));
const prop = curry((key, obj) => obj[key]);
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
// Pointed version
const revenuePointed = (os) =>
sum(os.filter((o) => o.paid).map((o) => o.total));
// Point-free version: no `os`, no `o`
const revenue = pipe(
filter(prop('paid')),
map(prop('total')),
sum
);
console.log(revenuePointed(orders)); // 100
console.log(revenue(orders)); // 100revenue reads as a list of steps: keep paid orders, take their totals, add them up. None of the intermediate values needs a name, so you cannot give one a misleading name either.
Gotchas and failure modes
Passing a function by reference is only safe when the function's signature matches what the caller sends. JavaScript does not check this for you. Most point-free bugs come from that mismatch.
Extra arguments from array methods
Array.prototype.map calls its callback with (element, index, array). If the function you pass accepts a second parameter, it receives the index.
console.log(['1', '2', '3'].map(parseInt)); // [ 1, NaN, NaN ]parseInt takes (string, radix), so the calls are parseInt('1', 0), parseInt('2', 1), and parseInt('3', 2). A radix of 0 falls back to base 10. Radix 1 is invalid, and '3' is not a valid base-2 digit. The fix is to pass a function that takes one argument, or to wrap the call with a unary helper:
const unary = (fn) => (x) => fn(x);
console.log(['1', '2', '3'].map(Number)); // [ 1, 2, 3 ]
console.log(['1', '2', '3'].map(unary(parseInt))); // [ 1, 2, 3 ]Optional parameters added later
This bug can show up long after you wrote the code. A function that works point-free today can break when someone adds an optional parameter to it.
const formatPrice = (amount, currency = 'USD') =>
`${currency} ${amount.toFixed(2)}`;
console.log([5, 10].map(formatPrice));
// [ '0 5.00', '1 10.00' ] (index was used as the currency)
console.log([5, 10].map((n) => formatPrice(n)));
// [ 'USD 5.00', 'USD 10.00' ]Before currency existed, map(formatPrice) was correct. Nothing at the call site changed, but the output did. When you pass a function you do not control, such as one from a library or another module, an explicit wrapper protects you from changes to its signature.
Losing `this`
When you pass a method by reference, you detach it from its object. Inside the call, this is undefined in strict mode.
'use strict';
const formatter = {
prefix: '#',
format(id) {
return this.prefix + id;
}
};
try {
[1, 2].map(formatter.format);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([1, 2].map(formatter.format.bind(formatter))); // [ '#1', '#2' ]
console.log([1, 2].map((id) => formatter.format(id))); // [ '#1', '#2' ]Without strict mode, this would be the global object, and you would get 'undefined1' instead of an error. That is worse, because the bug produces wrong output without failing. Point-free style works best with standalone functions that do not use this.
Arity and curry
The curry helper above uses fn.length, the number of declared parameters. fn.length does not count default parameters, rest parameters, or any parameter after the first default. A function written as (key, obj = {}) => ... has a length of 1, so curry calls it right away instead of waiting for obj. Keep functions you plan to curry free of defaults and rest parameters.
Readability and debugging costs
Point-free code removes names. Short pipelines of well-named helpers are easier to read without those names. Long pipelines, or ones built from generic combinators such as flip, converge, or nested compose calls, can become puzzles. The reader then has to work out the data's shape at each step in their head.
Debugging is also harder. You cannot add a console.log inside a function that has no body. A tap helper fixes this. It logs the value and passes it through unchanged:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const tap = (label) => (x) => {
console.log(label, x);
return x;
};
const process = pipe(
(xs) => xs.filter((n) => n > 1),
tap('after filter:'),
(xs) => xs.map((n) => n * 10)
);
console.log(process([1, 2, 3]));
// after filter: [ 2, 3 ]
// [ 20, 30 ]Stack traces suffer too. An error inside a pipeline points at the reduce inside pipe and at anonymous arrow functions. It does not point at a named function that describes the step. Giving each step a named const helps.
When to use it
| Situation | Recommendation |
|---|---|
| Callback only forwards its argument to a one-parameter function you own | Go point-free: `xs.map(toUpper)` |
| Short pipeline of named, curried, data-last helpers | Go point-free; it reads as a list of steps |
| Passing built-ins or library functions to `map`, `filter`, `forEach` | Wrap explicitly unless you have confirmed the function takes one argument |
| Passing object methods | Use an arrow wrapper or `bind` |
| You need generic combinators to remove the last argument | Keep the argument; the named version is clearer |
| Team is unfamiliar with curried helpers | Use pointed style and introduce point-free code gradually |
Point-free style is a tool for removing noise, and it is not something to aim for in itself. Name an argument whenever the name tells the reader something the code alone does not.
Exercise
Using the curried pipe, map, filter, and prop helpers from this chapter and const toUpper = (s) => s.toUpperCase(), rewrite const activeNames = (users) => users.filter((u) => u.active).map((u) => u.name.toUpperCase()); in point-free style.
Show answer
const activeNames = pipe(filter(prop('active')), map(pipe(prop('name'), toUpper))); The inner pipe builds the per-user step (take name, then uppercase it). The outer pipe filters first and then maps. No argument is named anywhere.
Exercise
Explain why ['10', '10', '10'].map(parseInt) returns [10, NaN, 2].
Show answer
map passes the index as the second argument, which parseInt treats as the radix. parseInt('10', 0) uses base 10 and returns 10. parseInt('10', 1) has an invalid radix and returns NaN. parseInt('10', 2) reads binary "10" and returns 2.
Exercise
A teammate writes ids.forEach(logger.log), where logger.log uses this.level. The code throws a TypeError in an ES module. Why, and what are two fixes?
Show answer
ES modules run in strict mode, so passing logger.log by reference detaches it from logger, and this is undefined inside the call. Two fixes: ids.forEach(logger.log.bind(logger)) or ids.forEach((id) => logger.log(id)). The arrow wrapper also stops forEach from passing the index and array as extra arguments.