Search code examples
javascriptmonads

Monads in JavaScript


So I want to understand the practical cases where monads in JavaScript are helpful.

I read a bunch on articles on Monads in JavaScript and understand that jQuery is one example of its use. But besides the "chaining" pattern, what other issues can be effectively solved using Monads in front-end engineering?

Ref:

http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/

http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html


Solution

  • Well I think the first article is great and quite detailed. It describes a lot of problems solved by JQuery and its monad nature.

    1. JQuery wraps the DOM elements and gives a richer interface. The problems solved are numerous : richer events ("mouseenter","mouseleave","hashchnged" etc.. ). Event binding adds handlers instead of overriding. The interface for CSS handling is similar to other interfaces exposed by JQuery.

    This is also the reason JQuery is so intuitive to a lot of developers as it simply wraps what we know and does not try to reinvent HTML.

    Not to mention that it saves a lot of errors when referring to nulls. If I don't have an element with id guy, then running $("#guy").text("I am not here") will not cause an error in JQuery.

    1. JQuery easily wraps itself around the DOM element allowing to traverse back and forward between raw JS and JQuery's interface. This allows developers to learn JQuery at their own pace instead of rewriting the entire code in one time.

    2. When JQuery feeds a callback with arguments, it uses the DOM object instead of JQuery's wrapper. This allows 3rd-parties to easily integrate with JQuery as they don't need to rely on JQuery. For example lets say I wrote a function that paints text in red using raw JavaScript. function paintRed(element){element.style.color="red"} - I can easily pass this function as callback to a JQuery function.