This blog entry provides a brief introduction to underscore.js mixins.


If you are not using underscore.js then I feel sorry for your code base. Underscore.js abstracts a lot of common routines and delegates to corresponding ES5 methods if they exist. It makes your life much easier and reduces noise in your code. Underscore.js also gives you the ability to create your own underscore.js functions in addition to the great ones included with underscore.js. Why is this good and please provide me with a use case.


I don’t know about you, but I am sick of writing and reading code like this.

if (obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2 === 42)

Underscore.js to the rescue, Now we can simly write the following.

if (_.validChain('obj.prop1.prop2', 42))

If you do not pass a truth test argument (42 in this case) then _.validChain() will return a boolean indicating whether or not the structure is valid. You can also pass a function as the truth test argument, e.g., function (test) { return 52 - 10 === test }.


Hopefully the code above speaks for itself. If not then try reading it again. Seriously though if it doesn't make sense or you feel that my approach is awful then comment on the gist,