Why Underscore is awesome

Underscore.js is a popular JavaScript library that contains 112 commonly needed helper functions.

These functions often aren't very complex, but you can use them to clearly communicate what your code is doing.

Compare these two bits of code, the first using just JavaScript and the second using Underscore:

list[list.length - 1]

vs.

_.last(list)

While Underscore doesn't save much code here, it makes the code easier to read than its plain JavaScript equivalent.

Another example. A common hack in JavaScript is to wait for all other processing to finish before running a particular bit of code.

This is done by setting a timeout with a wait time of 0 milliseconds:

setTimeout(newTask, 0)

By contrast, Underscore has a defer method - all it does is give a more meaningful name to "wait for 0 milliseconds":

_.defer(newTask)

Underscore is full of handy methods like these. Here are three more of them:

  • _.toArray(arguments) instead of Array.prototype.slice.call(arguments).
  • _.contains(list, item) instead of list.indexOf(item) !== -1.
  • _.isUndefined(value) instead of value === void(0)
Underscore helps you write code that clearly expresses your intentions

Instead of having to cater to the expectations of the JavaScript language, Underscore helps you write code that clearly expresses your intentions. The next developer - or the future you - will have an easier time understanding how you wanted your code to work.

True, you could write your own project-specific helper functions instead - but why bother when Underscore is well tested and only 6kb to download? Plus, knowledge of Underscore is transferable between projects and companies, which makes onboarding new developers easier.