Skip to content

What jQuery can teach you about monads

As I was laying in a hammock, pondering code, I had a strange thought/realization: jQuery leverages a monadic interface.

I’m writing this as a blog post so all my smart functional friends can disagree if I’m completely off base here, but let’s lay this out. Monads can be great for adding safety to your code, and reducing nesting. Monads help solve callback hell and can help you check for existence/types as you go. When I was chatting with my friend Soroush a few weeks ago about type safety, he said something super smart, and then gave me the link to this article on refactoring Ruby with monads:

the problem is the type safety lends itself to nesting
and when we have nesting, but we want flattening, we have to go to monads

I think that’s a super helpful way to think of monads. Monads can rescue you from nesting.

What’s jQuery got to do with it?

Ok, so let’s take this bit of jQuery code:

$('#non-existent').find('').css('color', 'red')

Now, as everyone learning JavaScript eventually writes some jQuery like this, they might not even process that at each stage, a failure does not cause the script to fail out. In essence, this little line of jQuery (and others like it) is implementing something like a Maybe (maybe). Try it yourself on a page with jQuery (basically anywhere on the internet; on this page, use `jQuery` rather than `$`).

What can I learn about monads?

I really think Soroush nailed something when he said that if you have nesting, but want flattening, you want monads. If you want to try and refresh yourself on the topic, you can also check out the Scary Words post on monads (read the comments as well!).

Even if jQuery doesn’t explicitly implement a monad (I’m sayin’ maybe it does? I’d have to read the source), using jQuery can definitely teach you a little something about monads, and maybe make them a little less scary.

2 Replies to “What jQuery can teach you about monads”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.