My simple and practical Intro to Monads in JS, where I covered basics of Identity and Maybe monads, seemed to be helpful for a lot of folks, so I’ve decide to continue the topic. Now it's time for Either - a tool for fast-failing, synchronous computation chains. A tool that may increase readability and quality of code while reducing error proneness. The best part is that we can still ignore the category theory!

An ounce of practice is generally worth more than a ton of theory.

Ernst F. Schumacher

All examples are based on monet.js - a tool bag that assists Functional Programming by providing a rich set of Monads and other useful functions. I'll use arrow functions introduced in ES6. They are much more readable than regular functions when used as single operation "callbacks". Also in most examples TypeScript type definitions will be added to enhance overall readability.

Do you remember the Maybe monad? The one that could have been Some(value) or Nothing? This is great when we have a function that can fail in one way - i.e .pop() from an array. If there's no element return Nothing. However, the Maybe monad loses expressivity when we have many things that can go wrong. E.g. getting some value from the encoded JSON - a corrupted JSON, an empty JSON or an empty field that should hold the value. We need a way to communicate multiple failures, or a success, enter Either.

It can have a value on either Right(value) or Left(error) side. For example Some(value) on the Right or an Error corresponding with Nothing on the Left (never both at the same time).

Behold the Either monad!

Either fail or success

Let's take a function from the previous article: