my-server
← Wiki

Underscore.js

Underscore.js is a JavaScript library which provides utility functions for common programming tasks. It is comparable to features provided by Prototype.js and the Ruby language, but opts for a functional programming design instead of extending object prototypes. The documentation refers to Underscore.js as "the tie to go along with jQuery's tux, and Backbone.js' suspenders." Underscore.js was created by Jeremy Ashkenas, who is also known for Backbone.js and CoffeeScript.

History

Jeremy Ashkenas created Underscore by the end of 2009 as a spin-off from the DocumentCloud project, together with Backbone.js. It was one of the earliest libraries for JavaScript to provide general functional programming utilities, taking inspiration from Prototype.js, Oliver Steele's Functional JavaScript, and John Resig's Micro-Templating.

In 2012, John-David Dalton created a fork of Underscore, named Lo-Dash (now Lodash). Lo-Dash was initially promoted as a drop-in alternative for Underscore with "consistency, customization, performance, & extras". Nevertheless, Lodash already departed from the original Underscore interface at an early stage and started making more drastic changes with the 3.0.0 release, making it necessary for Lodash users to change their code.

In May 2015, Jeremy Ashkenas announced that John-David Dalton had contacted him about merging the libraries back together. Despite concerns about code style and code size, Ashkenas was not opposed to merging some of Lodash's extensions into Underscore. At the time, there were several developers contributing to Underscore and Lodash in parallel; this group of contributors started making changes to Underscore in order to make it more like Lodash.

In parallel to this effort, however, Dalton made more drastic changes to the Lodash interface. In June 2015, he announced Lodash version 4.0.0, which distanced Lodash even further from the Underscore interface, while making a significant departure from the version 3.x series of Lodash itself as well. This prompted some projects that depended on Lodash to create their own distributions of Lodash 3.

In February 2016, Dalton announced that he considered the merge effort to be complete. He suggested that users switch from Underscore to Lodash, motivating this with usage share statistics. A maintainer of Underscore however made clear that there was no intention to stop developing Underscore as a separate library. Both libraries entered a state of low development activity after 2016.

Over time, newer versions of the ECMAScript standard have added built-in functions to the language that replicate some of the functionality of Underscore, such as <code>Object.assign</code> and <code>Array.prototype.map</code>. However, the built-in functions are sometimes less powerful than their Underscore equivalents; in particular, built-in array iteration methods such as <code>map</code>, <code>filter</code> and <code>forEach</code> cannot iterate over plain objects and do not support iteratee shorthands.

As of March 2021, Underscore is being actively developed by Julian Gonggrijp, who started making major contributions in March 2020. The library is still widely depended upon and is being downloaded from npm several million times every week.

Content

In essence, Underscore provides three things:

  1. A collection of more than 100 reusable functions, which are meant to be practically useful in everyday applications. The documentation distinguishes several categories:
  2. * Collection functions such as <code>find</code>, <code>map</code>, <code>min</code>/<code>max</code>, <code>groupBy</code> and <code>shuffle</code> process collections of data. These functions can operate on the elements of array-like sequences as well as on the properties of objects.
  3. * Array functions such as <code>first</code>/<code>last</code>, <code>flatten</code>, <code>chunk</code> and <code>zip</code> operate exclusively on array-like objects.
  4. * Function functions such as <code>bind</code>, <code>memoize</code>, <code>partial</code> and <code>debounce</code> take a function as argument and return a new function with altered properties (higher-order functions).
  5. * Object functions is a more foundational category, containing many functions that are also reused internally in Underscore. It can be roughly divided in two subcategories:
  6. ** Type testing functions such as <code>isNumber</code>, <code>isElement</code> and <code>isDataView</code>.
  7. ** Functions such as <code>keys</code>, <code>extend</code>, <code>pick</code>/<code>omit</code>, <code>pairs</code> and <code>invert</code>, which manipulate (plain) objects as data.
  8. * Utility functions is a rest category. Among others, it includes the trivial functions <code>identity</code> and <code>noop</code> and the string manipulating functions <code>escape</code>, <code>unescape</code> and <code>template</code>. This category also includes the functions <code>iteratee</code> and <code>mixin</code>, which could be considered special facilities as in point 2.
  9. Special facilities, such as <code>chain</code> and <code>iteratee</code>, which combine with the functions under point 1 in order to enable a shorter, cleaner syntax. The special function <code>_</code>, which the library is named after, is central to these facilities.
  10. Literate source code that is meant to be read, so that it is easy to follow how the library is implemented. The documentation includes a rendered version of the source code, where the comments are on the left and the logic is on the right. The comments are formatted using Markdown and the logic has syntax highlighting. Since version 1.11, Underscore is modular. For this reason, the documentation now includes both a modular version of the annotated source, in which each function is on a separate page and the <code>import</code> references are clickable hyperlinks, and a single read version, where all functions are on a single page by order of dependency.

Overview and examples of functions

Underscore promotes a functional style, where multiple functions can be combined in a single expression in order to obtain new functionality. For example, the following expression uses two Underscore functions to group words by their first characters:

Underscore functions are not in any way set apart from user-defined functions. Had the user implemented her own <code>first</code> function, the above expression would have worked equally well:

The set of functions provided by Underscore is however specifically chosen to minimize such effort, so that the user can compose functionality out of existing functions rather than writing her own.

Functions that iterate over the contents of an array or object usually take the data as the first parameter and an iterating function or iteratee as the second parameter. In the example above, <code>first</code> is the iteratee passed to <code>groupBy</code>.

Although the iteratee is not required to use them, it receives three arguments in most cases: (1) the value at the current position in the collection, (2) the key or index of this value and (3) the whole collection. In the following example, the second argument is used in an iteratee to <code>pick</code> in order to select only the properties of an object of which the key starts with an uppercase letter:

Many Underscore functions can be used as an iteratee, as previously illustrated with <code>first</code>. Apart from that, there are several common cases where the user can avoid writing an iteratee function, by using an iteratee shorthand instead. In the following example, the string <code>'name'</code> is used as an iteratee shorthand in order to extract all the <code>name</code> properties from an array of objects:

All functions in the "collection" category, including the <code>groupBy</code> and <code>map</code> functions demonstrated above, can iterate both over the indices of an array and over the keys of an object. This is illustrated below with <code>reduce</code>:

Besides functions that iterate over arrays or objects, Underscore provides a wide range of other reusable functions. For example, <code>throttle</code> limits the frequency with which a function is evaluated:

Another example is <code>defaults</code>, which assigns object properties only if not already set:

The <code>_</code> function

Underscore derives its name from the function <code>_</code>, which serves multiple purposes.

Wrapper function

As a function, <code>_</code> returns a wrapped version of any value that is passed as its first argument. This special object has all Underscore functions as methods, thus enabling a different notation that is referred to as "OOP style":

This feature is used in chaining (next section). The value can be unwrapped again with the <code>.value()</code> method in order to further process it outside of Underscore. Values also unwrap automatically in some cases.

Partial application placeholder

<code>_</code> also acts as a placeholder for the <code>partial</code> function. <code>partial</code> creates a partially applied version of a function and <code>_</code> can be used to leave some parameters "open" so that these can be supplied later. For example, the <code>groupBy</code> example from the overview can be extended as follows to turn the expression into a reusable function:

Customization point

Furthermore, <code>_</code> serves as a central customization point where users can adjust the behavior of Underscore functions to their needs. Specifically, users can override <code>_.iteratee</code> in order to create new iteratee shorthands, and <code>_.templateSettings</code> in order to customize the <code>template</code> function.

Namespace handle

More generally, all Underscore functions are present as properties on <code>_</code>, for example also <code>_.map</code> and <code>_.debounce</code>. This makes it possible to use <code>_</code> as a namespace handle. With the arrival of modules in ES6, having such a namespace handle is no longer strictly necessary, but the practice is still commonly found in code using older module systems such as AMD and CommonJS:

Given the existing practice, it can also be a convenient notation to clarify that one means a function specifically from the Underscore library and not a function with the same name from another library. For example, both Underscore and Async provide a function named <code>each</code>; to distinguish between them, one may write <code>_.each</code> and <code>async.each</code>, respectively.

Chaining

The function <code>chain</code> can be used to create a modified version of the wrapper produced by the <code>_</code> function. When invoked on such a chained wrapper, each method returns a new wrapper so that the user can continue to process intermediate results with Underscore functions:

It is not uncommon for a function implemented with Underscore to consist entirely of a <code>return</code> statement with a chain ending in <code>.value()</code>:

Chaining is not exclusive to the functions that ship with Underscore. Users can enable chaining for their own functions as well by passing them to the <code>mixin</code> function:

In fact, this is exactly how chaining is enabled for Underscore's own functions as well. All Underscore functions are written as regular standalone functions, without any special preparations for chaining, and then "mixed into" the <code>_</code> function afterwards.

Iteratee shorthands

As previously mentioned in the overview, most Underscore functions that iterate over arrays or objects accept a shorthand notation as iteratee instead of a function. Repeating the example from that section here:

Under the hood, this notation is enabled by passing the shorthand value through <code>_.iteratee</code> in order to obtain a function. <code>_.iteratee</code> defaults to the <code>iteratee</code> function that ships with Underscore, which, depending on the value, returns a function as follows.

Paths

When the value is a string, <code>iteratee</code> forwards the value to <code>property</code>, which interprets the string as a property key. It returns a function that attempts to extract the property with the given key from its argument. The following expressions are all equivalent:

Arrays and numbers are also passed to <code>property</code>. Arrays can be used to retrieve nested properties:

Numbers can be used as array and string indices. Combining all of this, we can use the following expression to count how many times letters of the alphabet occur as the second character of a person's occupation:

Attribute hashes

When the value is an object, <code>iteratee</code> forwards it to <code>matcher</code>, which interprets the object as a set of attributes that must be matched. It returns a function that will return <code>true</code> or <code>false</code> depending on whether its argument has this same set of attributes.

<code>null</code> and <code>undefined</code>

When the value is <code>null</code> or <code>undefined</code>, <code>iteratee</code> returns the identity function that Underscore exports as <code>identity</code>. This can be used to filter out the truthy values from a collection:

Overriding <code>_.iteratee</code>

Users can override _.iteratee in order to create custom shorthands. The following example illustrates how one may use this to implement regular expression filtering:

See also

References

External links