Recently I was reading this article by Josh Haberman describing monads as a design pattern. I’m one of the many who has rammed their head into the brick wall that is understanding what monads are, but I haven’t read an article about them in a while so I figured Maybe today would be the day.
And it was.
It probably had more to do with the learning process than anything else, but I think describing them as a design pattern is great, so I’m gonna take a crack at bringing that approach to JavaScript-land by describing a practical monad. In part two, I’ll go over implementing it. I love math, but I’m gonna try keeping these posts as concrete as possible.
So on with the show.
For our example, we’ll go ahead and use the Maybe monad. But first, we should talk for a second about exactly what a monad is. There are a couple of ways to approach this answer. I don’t know enough about category theory to take that route, and I really want to make this post about JavaScript, so I’m gonna explain it as best as I can in simple JavaScript terms.
A monad is an object.
*mind blown*
We’ll define a Maybe object as being an object that can either have some value or be undefined.
var maybe = new Maybe("Hello!");var nothing = new Maybe(undefined);
Here’s the powerful thing about monads: virtually any function can be applied to them. This is because of a special method they have called “bind.” Since “bind” is already well defined in JavaScript, we’ll go ahead and borrow Josh Haberman’s terminology and call it “andThen.”
maybe.andThen(console.log);
> Hello!nothing.andThen(console.log);
> // literally does nothing
There are probably red flags waving in your head right now. That’s the beauty of monads, though. You can describe how functions are applied to them. YOU have the power to decide what they do. In my next post, I’ll be giving you a glimpse into how you can do that for your own monads.