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:
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.