Underscore.js

Underscore.js is a JavaScript library which provides utility functions for common programming tasks.

Uses your system voice; voice and rate in settings.

Snapshot

≈ 8 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

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. import { groupBy, first } from 'underscore'; groupBy(['avocado', 'apricot', 'cherry', 'date', 'durian'], first); // result: // { a: ['avocado', 'apricot'], // c: ['cherry'], // d: ['date', 'durian'] // } Underscore functions are not in any way set apart from user-defined functions. Had the user implemented her own first function, the above expression would have worked equally well: import { groupBy } from 'underscore'; const first = array => array[0]; groupBy(['avocado', 'apricot', 'cherry', 'date', 'durian'], first); 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, first is the iteratee passed to groupBy .

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 pick in order to select only the properties of an object of which the key starts with an uppercase letter: import { pick } from 'underscore'; const details = { Official: 'Wolfgang Amadeus Mozart', informal: 'Wolfie' }; const keyIsUpper = (value, key) => key[0] === key[0].toUpperCase(); pick(details, keyIsUpper); // {Official: 'Wolfgang Amadeus Mozart'} Many Underscore functions can be used as an iteratee, as previously illustrated with first .

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 'name' is used as an iteratee shorthand in order to extract all the name properties from an array of objects: import { map } from 'underscore'; const people = [ {name: 'Lily', age: 44, occupation: 'librarian'}, {name: 'Harold', age: 10, occupation: 'dreamer'}, {name: 'Sasha', age: 68, occupation: 'library developer'} ]; map(people, 'name'); // ['Lily', 'Harold', 'Sasha'] All functions in the "collection" category, including the groupBy and map functions demonstrated above, can iterate both over the indices of an array and over the keys of an object.

This is illustrated below with reduce : import { reduce } from 'underscore'; const add = (a, b) => a + b; const sum = numbers => reduce(numbers, add, 0); sum([11, 12, 13]); // 36 sum({Alice: 9, Bob: 9, Clair: 7}); // 25 Besides functions that iterate over arrays or objects, Underscore provides a wide range of other reusable functions. For example, throttle limits the frequency with which a function is evaluated: import { throttle } from 'underscore'; // The scroll event triggers very often, so the following line may // slow down the browser. document.body.addEventListener('scroll', expensiveUpdateFunction); // Limit evaluation to once every 100 milliseconds. const throttledUpdateFunction = throttle(expensiveUpdateFunction, 100); // Much smoother user experience! document.body.addEventListener('scroll', throttledUpdateFunction); Another example is defaults , which assigns object properties only if not already set: import { defaults } from 'underscore'; const requestData = { url: 'wikipedia.org', method: 'POST', body: 'article text' }; const defaultFields = { method: 'GET', headers: {'X-Requested-With': 'XMLHttpRequest'} }; defaults(requestData, defaultFields); // { // url: 'wikipedia.org', // method: 'POST', // body: 'article text', // headers: {'X-Requested-With': 'XMLHttpRequest'} // } import _, { last } from 'underscore'; // "Normal" or "functional" style last([1, 2, 3]); // 3 // "OOP style" _([1, 2, 3]).last() // 3 This feature is used in chaining (next section).

The value can be unwrapped again with the .value() method in order to further process it outside of Underscore. Values also unwrap automatically in some cases. // Explicit unwrap _([1, 2, 3]).value() // [1, 2, 3] // Automatic unwrap when coerced to number 1 + _(2) // 3 // Automatic unwrap when coerced to string 'abc' + _('def') // 'abcdef' // Automatic unwrap when formatted as JSON JSON.stringify({ a: _([1, 2]) }) // '{"a":[1,2]}' import _, { partial, groupBy, first } from 'underscore'; const groupByFirstChar = partial(groupBy, _, first); groupByFirstChar(['avocado', 'apricot', 'cherry', 'date', 'durian']); // { a: ['avocado', 'apricot'], // c: ['cherry'], // d: ['date', 'durian'] // } groupByFirstChar(['chestnut', 'pistache', 'walnut', 'cashew']); // { c: ['chestnut', 'cashew'], // p: ['pistache'], // w: ['walnut] // } var _ = require('underscore'); _.groupBy(['avocado', 'apricot', 'cherry', 'date', 'durian'], _.first); 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 each ; to distinguish between them, one may write _.each and async.each , respectively. import { chain } from 'underscore'; const square = x => x * x; const isOdd = x => x % 2; chain([1, 2, 3, 4]).filter(isOdd).map(square).last() // returns a wrapper of 9 It is not uncommon for a function implemented with Underscore to consist entirely of a return statement with a chain ending in .value() : const add = (x, y) => x + y; // Given an array of numbers, return the sum of the squares of // those numbers. This could be used in a statistics library. function sumOfSquares(numbers) { return chain(numbers) .map(square) .reduce(add) .value(); } 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 mixin function: import { reduce, mixin } from 'underscore'; const sum = numbers => reduce(numbers, add, 0); mixin({ sum, square }); chain([1, 2, 3]).map(square).sum().value(); // 14 chain([1, 2, 3]).sum().square().value(); // 36 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 _ function afterwards. import { map } from 'underscore'; const people = [ {name: 'Lily', details: {age: 44, occupation: 'fire fighter'}}, {name: 'Harold', details: {age: 10, occupation: 'dreamer'}}, {name: 'Sasha', details: {age: 68, occupation: 'library developer'}} ]; map(people, 'name'); // ['Lily', 'Harold', 'Sasha'] Under the hood, this notation is enabled by passing the shorthand value through _.iteratee in order to obtain a function. _.iteratee defaults to the iteratee function that ships with Underscore, which, depending on the value, returns a function as follows. import { iteratee, property } from 'underscore'; map(people, 'name'); map(people, iteratee('name')); map(people, property('name')); map(people, obj => obj && obj['name']); // ['Lily', 'Harold', 'Sasha'] Arrays and numbers are also passed to property .

Arrays can be used to retrieve nested properties: map(people, ['details', 'occupation']); // ['fire fighter', 'dreamer', 'library developer'] 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: import { countBy } from 'underscore'; countBy(people, ['details', 'occupation', 1]); // {i: 2, r: 1} import { find } from 'underscore'; find(people, {name: 'Sasha'}); // {name: 'Sasha', details: {age: 68, occupation: 'library developer'}} find(people, {name: 'Walter'}); // undefined import { filter, iteratee, identity } from 'underscore'; const example = [0, 1, , 'abc', true, false, {}]; // The following expressions are all equivalent. filter(example); filter(example, undefined); filter(example, iteratee(undefined)); filter(example, identity); // [1, 'abc', true, {}] import { iteratee as originalIteratee, isRegExp, mixin, filter, } from 'underscore'; function iteratee(value, context) { if (isRegExp(value)) { return string => value.test(string); } else { return originalIteratee(value, context); } } mixin({iteratee}); filter(['absolutely', 'amazing', 'fabulous', 'trousers'], /ab/); // ['absolutely', 'fabulous']

Text derived from https://en.wikipedia.org/w/index.php?oldid=1377702250 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

25 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.