The vocabulary comes from the Fantasy Land specification, a community spec (not part of ECMAScript) that names the algebra and its laws.
- A functor is a container with
mapthat obeys two laws: mapping the identity function changes nothing, andm.map(x => f(g(x)))equalsm.map(g).map(f). - A monad adds
of(wrap a value) andchain(map with a function that returns a wrapped value, then remove one layer). It obeys left identity (of(a).chain(f)equalsf(a)), right identity (m.chain(of)equalsm) and associativity.
Arrays fit. map is the functor operation; x => [x] is of; flatMap is chain. In the spec, flatMap calls FlattenIntoArray with depth 1: each result that passes IsArray is spread one level, and anything else is appended as a value. Nested arrays inside a result stay nested, which is exactly what the laws need.
Promises nearly fit. Promise.resolve is of, and then plays both roles: if the callback returns a plain value, then behaves like map; if it returns a promise, like chain. The break is in the promise resolve function. It reads .then from any object it's resolved with and, if it's callable, adopts that thenable's eventual value, recursively. So a promise can never be fulfilled with a thenable, a Promise of a Promise can't exist, and the functor and monad laws fail whenever a value happens to be thenable.
So in an interview: "Monad-like, not a lawful monad." For everyday code the auto-flattening is a convenience, and the laws do hold for values that aren't thenables. It matters when you write generic code over "any container", or when your own objects happen to have a then method.