Back to results for “Functional Programming”
JavaScript › Functional Programming

What are functors and monads, at a practical level, and does JavaScript have native support for them?

Advanced

Answer

A functor is any structure with a .map() method that applies a function to its wrapped value while keeping the wrapper (Array and Promise both qualify). A monad additionally has a way to 'flatten' nested wrappers (like Promise's automatic chaining, or Array's flatMap). JavaScript doesn't enforce these as formal types, but Array and Promise both behave like a functor/monad in practice.
// Array as a functor
[1,2,3].map(n => n * 2); // [2,4,6]

// Promise behaves monad-like: chained then() auto-flattens nested promises
Promise.resolve(1).then(n => Promise.resolve(n + 1)).then(console.log); // 2
Real-world example Recognizing that chaining .then() on Promises already gives you monad-like flattening for free, without needing a library.

Common follow-ups: Do libraries like Ramda or fp-ts provide more formal functor/monad implementations?