Monads

Learn about monads and their usage with the help of coding examples.

How can we avoid exceptions? How will we handle error cases without them? If Promises aren’t ideal for asynchronous behavior, what should we use instead? Enter the dreaded monads!

What are monads?

Many articles explain monads, some from their mathematical beginnings, others using a broad range of examples. Here, it might suffice to compare them to a container. We have a certain value (a string, a number, or an object), and we put it inside that container. In several functional languages, putting the value inside the monad is called return. But, because return is a keyword in JavaScript, we’ll find various other words for it, like of.

Note: The various constructors for monads in fp-ts are called lifting functions.

Note: Some in the functional programming world dislike the container comparison, probably because it oversimplifies things. On the other hand, the comparison is easy to grasp and useful in most cases.

Functors

We have a value inside a container. What does that get us? Well, monads have several functions that influence or change that value. For example, the monad function map takes a function that might be applied to the value inside the container. Why do we say “might”?

Note: Technically, monads only define bind, chain, or flatmap methods, but not a map, which is part of the definition of a ...