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('a.cool-link').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.

Be Sociable, Share!

Tags: , ,

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

  1. Jon Moore February 7, 2015 at 5:42 pm #

    Cool post! This intrigued me so much I went and carried out the exercise you suggested at the end!


  2. Andrew February 16, 2015 at 2:28 pm #

    There are certain features it has that means it lacks certain features are that means it isn’t one. The “double wrapping” and lack of strictness are two important ones:

Leave a Reply