Sub topic 16
Containers, Functors, and Maybe
This chapter assumes you know arrow functions, closures, and map on arrays. It also assumes you have read the chapter on composing functions with pipe and compose. You will learn what a container is and what makes one a functor. Then you will build a Maybe container that handles missing values without repeated if (x != null) checks.
The Idea of a Container
A container is a value wrapped in an object, together with a fixed way to work on what is inside. You do not take the value out, change it, and put it back. You hand the container a function, and the container decides how to apply it.
The simplest container is Box, which always applies the function:
const Box = (value) => ({
map: (fn) => Box(fn(value)),
fold: (fn) => fn(value),
toString: () => `Box(${value})`
});
const result = Box(' 42 ')
.map((s) => s.trim())
.map((s) => Number(s))
.map((n) => n + 1);
console.log(String(result)); // Box(43)
console.log(result.fold((n) => n)); // 43map returns a new Box, so calls chain. fold is how you finally take the value out. Box adds no behavior beyond pipe, but it sets up the pattern that every container in this chapter follows: wrap, map, unwrap.
What Makes a Functor
A functor is a container with a map method that obeys two laws. You already use one every day, because Array is a functor.
| Law | Statement | Array example |
|---|---|---|
| Identity | `c.map(x => x)` equals `c` | `[1, 2].map(x => x)` gives `[1, 2]` |
| Composition | `c.map(f).map(g)` equals `c.map(x => g(f(x)))` | Two passes give the same result as one pass with the composed function |
const id = (x) => x;
const f = (x) => x + 1;
const g = (x) => x * 2;
const xs = [1, 2, 3];
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
console.log(same(xs.map(id), xs)); // true
console.log(same(xs.map(f).map(g), xs.map((x) => g(f(x))))); // trueThese laws matter because they let you refactor safely. If map is lawful, you can merge two map calls into one or split one into two, and nothing about the result changes. A map that also logs, counts calls, or changes behavior depending on the function breaks that guarantee.
Building Maybe
Maybe represents a value that might be missing. When the value is null or undefined, the container is called Nothing. Otherwise it is called Just. map runs the function on a Just and skips it on a Nothing.
const Maybe = (value) => ({
isNothing: () => value == null,
map: (fn) => (value == null ? Maybe(null) : Maybe(fn(value))),
chain: (fn) => (value == null ? Maybe(null) : fn(value)),
getOrElse: (fallback) => (value == null ? fallback : value),
toString: () => (value == null ? 'Nothing' : `Just(${JSON.stringify(value)})`)
});
const cityOf = (user) =>
Maybe(user)
.map((u) => u.address)
.map((a) => a.city)
.map((c) => c.toUpperCase())
.getOrElse('Unknown');
console.log(cityOf({ address: { city: 'Lagos' } })); // LAGOS
console.log(cityOf({ address: {} })); // Unknown
console.log(cityOf(null)); // UnknownEvery step in cityOf is written as if the value exists. The null check sits in one place, inside map, so the functions you pass in stay small and simple. Once one step produces undefined, every later map is skipped, and getOrElse supplies the fallback.
The loose equality check is deliberate
value == null is true only for null and undefined. That is the one place in modern JavaScript where == is the right tool. A common bug is to write !value instead, which turns 0, '', false, and NaN into Nothing:
const BadMaybe = (value) => ({
map: (fn) => (!value ? BadMaybe(null) : BadMaybe(fn(value))),
getOrElse: (fallback) => (!value ? fallback : value)
});
console.log(Maybe(0).map((n) => n + 1).getOrElse(-1)); // 1
console.log(BadMaybe(0).map((n) => n + 1).getOrElse(-1)); // -1 (wrong)map vs. chain: Avoiding Nested Containers
Some functions already return a Maybe. A safe JSON parser is one example:
const safeParse = (text) => {
try {
return Maybe(JSON.parse(text));
} catch {
return Maybe(null);
}
};If you pass safeParse to map, you get a Maybe inside a Maybe. The next map receives the inner container object instead of the parsed config:
const portWithMap = (raw) =>
Maybe(raw)
.map(safeParse) // Maybe(Maybe(config))
.map((c) => c.port) // c is a Maybe object, c.port is undefined
.getOrElse(3000);
const portWithChain = (raw) =>
Maybe(raw)
.chain(safeParse) // Maybe(config)
.map((c) => c.port)
.getOrElse(3000);
console.log(portWithMap('{"port":8080}')); // 3000 (silently wrong)
console.log(portWithChain('{"port":8080}')); // 8080
console.log(portWithChain('not json')); // 3000
console.log(portWithChain(undefined)); // 3000chain (also called flatMap or bind) runs the function and returns its result without wrapping it again. The rule is short:
- Use
mapwhen the function returns a plain value. - Use
chainwhen the function returns aMaybe.
Arrays follow the same rule. [1, 2].map((x) => [x, x]) gives nested arrays, and [1, 2].flatMap((x) => [x, x]) gives [1, 1, 2, 2].
Fitting Maybe into pipe
Method chaining works, but you can also make map and chain standalone, curried functions. Then they slot into pipe from the composition chapter:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const map = (fn) => (m) => m.map(fn);
const chain = (fn) => (m) => m.chain(fn);
const getOrElse = (fallback) => (m) => m.getOrElse(fallback);
const prop = (key) => (obj) => obj[key];
const portFromConfig = pipe(
Maybe,
chain(safeParse),
map(prop('server')),
map(prop('port')),
getOrElse(3000)
);
console.log(portFromConfig('{"server":{"port":9000}}')); // 9000
console.log(portFromConfig('{"server":{}}')); // 3000The pipeline now reads as a list of steps, with no explicit argument anywhere. This is point-free style applied to containers.
Maybe vs. Optional Chaining
Since ES2020, JavaScript has ?. and ??, which cover the simplest case directly:
const user = { address: { city: 'Lagos' } };
console.log(user?.address?.city?.toUpperCase() ?? 'Unknown'); // LAGOS| Concern | `?.` and `??` | `Maybe` |
|---|---|---|
| Property access on possibly missing data | Built in, no library needed | Works, but more verbose |
| Running arbitrary functions in sequence | Needs a temporary variable or a ternary at each step | `map` and `chain` |
| Reusable, composable steps | No, it is syntax | Yes, steps are plain functions |
| Readability for teammates | Familiar to all JS developers | Requires learning the pattern |
| Explaining why a value is missing | No | No (see Either below) |
For plain property lookups, use optional chaining. Maybe is worth it when the steps are functions, such as parsing, lookups, and validation, and you want to compose them and reuse them across pipelines.
Edge Cases and Limits
- Exceptions still escape.
Maybehandles absence, not failure. If a function you pass tomapthrows, the error propagates. Wrap risky calls, assafeParsedoes. - Nothing carries no reason. When
portFromConfigreturns3000, you cannot tell whether the input was missing, invalid JSON, or lacked aserverkey. TheEithercontainer fixes this with a Left branch that carries an error value. It follows the samemapandchainpattern. - Promises are almost functors.
thenacts likemapandchainat once, because it flattens any promise the callback returns. That convenience breaks the composition law for functions that return promises. Treatthenas a practical tool, not a lawful functor. - Allocation cost. Each
mapcreates a new object. In normal code this does not matter. In a hot loop over millions of items, measure the cost before adopting the pattern.
Exercise
Write a function findUser(users, id) that returns a Maybe holding the user with the given id. Then use it with chain and map to get that user's email in lowercase, falling back to 'none'. Should findUser be passed to map or chain, and why?
Show answer
const findUser = (users, id) => Maybe(users.find((u) => u.id === id)); Then Maybe(users).chain((us) => findUser(us, 2)).map((u) => u.email).map((e) => e.toLowerCase()).getOrElse('none'). Use chain, because findUser already returns a Maybe. Passing it to map would give Maybe(Maybe(user)), and the next map would read .email off the inner container object, getting undefined and silently returning 'none'.
Exercise
Someone changes Maybe's map to map: (fn) => { console.log('mapping'); return value == null ? Maybe(null) : Maybe(fn(value)); }. Do the functor laws still hold for the returned values? What practical guarantee is lost?
Show answer
The returned values still satisfy both laws, because the logging does not change the result. But m.map(f).map(g) now logs twice while m.map(x => g(f(x))) logs once, so the two forms are no longer interchangeable in observable behavior. The side effect removes the freedom to merge or split map calls without changing what the program does.
Exercise
What does Maybe('').map((s) => s.length).getOrElse(-1) return with this chapter's Maybe, and what would it return if map used !value instead of value == null?
Show answer
With value == null, the empty string counts as a real value, so the result is 0. With !value, the empty string is falsy and treated as Nothing, so the result is -1. That is wrong, because an empty string is present data, not missing data.