It’s a **simple, practical tutorial** for JavaScript developers display how some monads can be used. It’s for engineers, not scientists. In theory, there is no inequality between theory and practice. In practice there is.

All examples are based on **monet.js** – *a tool bag that assists working Programming by providing a rich set of Monads and other useful functions.* I’ll use **arrow functions **introduced in ES6.

They are much more coherent than regular functions when used as single operation *“callbacks”*. Also, in some examples, **TypeScript** type definitions will be additional to enhance overall readability.

# Monad

**Monad** is a box containing some value. People say it has the entity to do with freaky **category theory** but we can forget that fact. Our box is not just a wrapper. It has tools to bind calculations to the value. It can serve multiple distant purposes – asynchronicity, fail-fast, error accumulation, lazy evaluation, etc… but these will be painted in future articles.

It’s called `bind`

(or `flatMap`

) and has to meet 3 requirements:

– `bind`

takes one parameter – a function (let’s call it `callback`

)

– `callback`

takes current value and arrival monad containing a result of calculation

– `bind`

returns a monad returned by `callback`

And TypeScript definition:

# Identity

Axioms tell us that there should be some function that organize a monad. Consider we have `Identity(value)`

function that does the job:

But why should I ever convolute my life so much if all I want is to add two integers? Right. The previous example is not a real life one at all. But we can try to `.bind()`

several action to some value. And we may use another common (in monad world) method – `.map()`

. When measuring you don’t have to return a monad from`callback`

– returned value is protected under the hood in the same monad:

So let’s do some real computation:

An `.map()`

in `Identity`

works exactly like in an `Array`

:

For the purpose of this example, calculations above are fairly simple but they show an idea of how to belong to operations in descriptive, readable way. Consider another potential:

or in more functional style:

# Promise A/A+

Common JavaScript **Promises** are quite similar to monads. They are boxed incorporate values (or rejections). Compare this serving of code with initial`Identity`

example:

It is a simple example. Actually, Promise A/A+ is not as types as Monads are. The method `.then()`

is so elastic that it does a job of a few different methods of a monad (`bind`

/`flatMap`

, `map`

, `orElse`

, `cata`

and few more).

But for sure there exist monadic application of JavaScript!`Promise`

# Maybe

There are several monads in the wild. Probably the most accepted is Maybe (Option). It can be `Some(value)`

or `Nothing`

. Example that fits previous ones:

It turns into useful when we have methods/functions rebound some value or`null`

/`undefined`

. For example `getCurrentUser()`

:

Maybe has few base methods:

– `flatMap`

which is core of any monad

– `map`

lets us get `Maybe`

from `Maybe`

– `filter`

lets us change `Some`

into `None`

if a condition is not met

– `orSome`

– get monad value *or just* another value

– `orElse`

– get monad (if is `Some`

) or else newly passed monad

– `cata`

– whooo lot of magic…

## Let’s `.filter()`

and `.map()`

like an Array

If you treat an `Maybe`

as a single element (`Some`

) or empty (`None`

) array – `map`

and`filter`

will work the same:

# So let’s `.flatMap()`

…but that is still a bit frightful. And that’s why my favorite JavaScript application (**monet.js**) provides added way to **create** a Maybe monad:

# Maybe tea `.orElse()`

maybe coffee…

We have studied a default value for the optional name field. We may also wish to fill it with an optional value from any other farmland in our source value like`'nickname'`

. Here’s what can we do with the filthy imperative tools:

# Conclusion

This simple little monad can save you a lot of points and some code. `Identity`

gives you ability to write complex calculation as descriptive steps. `Maybe`

brings protection from `Cannot read property of null`

exceptions. And what is most great – it’s only first step to a functional programming monadic world where you can find more very much alike tools like `Either`

(fail-fast handling),`Validation`

(error accumulation), `Promise`

(async operations), immutable,`List`

`Lazy`

, `Continuation`

, `Free`

, `Read`

, etc… **And some of them will be covered here shortly!**

**See more:**

**Best JavaScript Resources to add Voice Control**