Sub topic 16
Containers, Functors, and Maybe
This chapter assumes you are comfortable with higher-order functions, function composition with pipe, and the idea of isolating side effects. It covers the working model of a container, the rules that make a container a functor, and the mistakes people make most often with Maybe.
Values in a Box
A container is an object that holds a value and controls how functions reach it. You never take the value out to work on it. Instead, you pass a function in through map, and you get back a new container.
const Box = (x) => ({
map: (fn) => Box(fn(x)),
fold: (fn) => fn(x)
});
const result = Box(' 42 ')
.map((s) => s.trim())
.map(Number)
.map((n) => n * 2)
.fold((n) => n);
console.log(result); // 84Box adds no behavior. It does show the shape, though: a chain of map calls is function composition written left to right, and fold is the one place where the value leaves the container.
What Makes a Functor
A functor is a container with a map method that obeys two laws:
| Law | Statement | Meaning |
|---|---|---|
| Identity | `F(x).map(v => v)` equals `F(x)` | Mapping does nothing extra by itself |
| Composition | `F(x).map(f).map(g)` equals `F(x).map(v => g(f(v)))` | Chained maps can be fused into one |
Array.prototype.map follows both laws, so arrays are functors. Because of these laws you can refactor a chain of maps without changing its behavior.
Maybe: Skipping Work When the Value Is Missing
Maybe is a functor whose map checks the value before calling your function. If the value is null or undefined, map skips the function and passes the empty container along.
const Maybe = (value) => ({
map: (fn) => (value == null ? Maybe(null) : Maybe(fn(value))),
getOrElse: (fallback) => (value == null ? fallback : 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({})); // Unknown
console.log(cityOf(null)); // UnknownFor plain property access, JavaScript's built-in user?.address?.city?.toUpperCase() ?? 'Unknown' does the same job. Maybe is the better fit when the steps are arbitrary functions, such as parsers or lookups, that you want to compose and reuse.
Common Errors
- Testing for falsiness instead of null. If you write
!valueinstead ofvalue == null, valid values such as0,'', andfalseget dropped. - Nesting containers. If
fnitself returns aMaybe, thenmapwraps it again and you getMaybe(Maybe(x)). To avoid this you need achain(also calledflatMap) method that does not re-wrap. - Unwrapping too early. Calling
getOrElsein the middle of a pipeline brings the null checks back. Unwrap once, at the edge of your program. - Side effects inside
map.mapis for transforming values. Logging or mutating inside it breaks the guarantees the functor laws give you.
Exercise
Using the Maybe defined above, what does Maybe(0).map((n) => n + 1).getOrElse(-1) return, and what would it return if map tested !value instead of value == null?
Show answer
It returns 1, because 0 is not null or undefined, so the function runs. With a !value check, 0 would count as missing: map would skip the function and getOrElse would return -1.
Exercise
Write a safeProp(key) function that returns a function taking an object and producing a Maybe, then use it with a chain method to read user.address.city.
Show answer
const safeProp = (key) => (obj) => Maybe(obj == null ? null : obj[key]); then Maybe(user).chain(safeProp('address')).chain(safeProp('city')).getOrElse('Unknown'). Using chain instead of map stops the Maybe from being wrapped twice.