What does _(variable_name) mean in javascript?

Came looking for an answer to this and managed to find one. The _(variable) statement wraps underscore around the variable. According to this link in the "Object-Oriented and Functional Styles" section,

index = _(children).indexOf(target);

is equivalent to

index = _.indexOf(children, target);

The first is written in object-oriented style, which allows chaining of functions. Their example is as follows:

_(lyrics).chain()
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce({}, function(counts, word) { 
    counts[word] = (counts[word] || 0) + 1;

Each of these functions returns the underscore function wrapping lyrics, allowing chained manipulation of the lyrics variable.

Underscore changelog:

0.4.0 — November 7, 2009: All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.


_ is a valid variable identifier in JavaScript, and could theoretically refer to anything. Using _(...) with function syntax implies that _ is a function.

That said, it is commonly used by the underscore.js library, however if you're looking at minified code, it's quite possibly being used as another single-character variable name to save on file size.


In your example provided, it appears that underscore.js is being used to treat children as a collection, so that the indexOf function can be applied to the collection. This would be similar to calling:

_.indexOf(children, target);

class Book {
  constructor(author) {
    this._author = author;
}

It is convention to precede the name of a private variable with an underscore (_). However, the practice itself does not make a variable private.

Tags:

Javascript