noConflict

_.noConflict() source

Give control of the global _ variable back to its previous owner. Returns a reference to the Underscore object.

  1. var underscore = _.noConflict();

The _.noConflict function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore.

identity

_.identity(value) source

Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.

  1. var stooge = {name: 'moe'};
  2. stooge === _.identity(stooge);
  3. => true

constant

_.constant(value) source

Creates a function that returns the same value that is used as the argument of _.constant.

  1. var stooge = {name: 'moe'};
  2. stooge === _.constant(stooge)();
  3. => true

noop

_.noop() source

Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

  1. obj.initialize = _.noop;

times

_.times(n, iteratee, [context]) source

Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.

  1. _.times(3, function(n){ genie.grantWishNumber(n); });

random

_.random(min, max) source

Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

  1. _.random(0, 100);
  2. => 42

mixin

_.mixin(object) source

Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper. Returns the Underscore object to facilitate chaining.

  1. _.mixin({
  2. capitalize: function(string) {
  3. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  4. }
  5. });
  6. _("fabio").capitalize();
  7. => "Fabio"

iteratee

_.iteratee(value, [context]) source

Generates a callback that can be applied to each element in a collection. .iteratee supports a number of shorthand syntaxes for common callback use cases. Depending upon value’s type, .iteratee will return:

  1. // No value
  2. _.iteratee();
  3. => _.identity()
  4. // Function
  5. _.iteratee(function(n) { return n * 2; });
  6. => function(n) { return n * 2; }
  7. // Object
  8. _.iteratee({firstName: 'Chelsea'});
  9. => _.matcher({firstName: 'Chelsea'});
  10. // Anything else
  11. _.iteratee('firstName');
  12. => _.property('firstName');

The following Underscore methods transform their predicates through _.iteratee: countBy, every, filter, find, findIndex, findKey, findLastIndex, groupBy, indexBy, map, mapObject, max, min, partition, reject, some, sortBy, sortedIndex, and uniq

You may overwrite _.iteratee with your own custom function, if you want additional or different shorthand syntaxes:

  1. // Support `RegExp` predicate shorthand.
  2. var builtinIteratee = _.iteratee;
  3. _.iteratee = function(value, context) {
  4. if (_.isRegExp(value)) return function(obj) { return value.test(obj) };
  5. return builtinIteratee(value, context);
  6. };

uniqueId

_.uniqueId([prefix]) source

Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

  1. _.uniqueId('contact_');
  2. => 'contact_104'

escape

_.escape(string) source

Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

  1. _.escape('Curly, Larry & Moe');
  2. => "Curly, Larry &amp; Moe"

unescape

_.unescape(string) source

The opposite of escape, replaces &, <, >, ", ` and ' with their unescaped counterparts.

  1. _.unescape('Curly, Larry &amp; Moe');
  2. => "Curly, Larry & Moe"

result

_.result(object, property, [defaultValue]) source

If the value of the named property is a function then invoke it with the object as context; otherwise, return it. If a default value is provided and the property doesn’t exist or is undefined then the default will be returned. If defaultValue is a function its result will be returned.

  1. var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
  2. _.result(object, 'cheese');
  3. => "crumpets"
  4. _.result(object, 'stuff');
  5. => "nonsense"
  6. _.result(object, 'meat', 'ham');
  7. => "ham"

now

_.now() source

Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.

  1. _.now();
  2. => 1392066795351

template

_.template(templateString, [settings]) source

Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate values, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>. When you evaluate a template function, pass in a data object that has properties corresponding to the template’s free variables. The settings argument should be a hash containing any _.templateSettings that should be overridden.

  1. var compiled = _.template("hello: <%= name %>");
  2. compiled({name: 'moe'});
  3. => "hello: moe"
  4. var template = _.template("<b><%- value %></b>");
  5. template({value: '<script>'});
  6. => "<b>&lt;script&gt;</b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

  1. var compiled = _.template("<% print('Hello ' + epithet); %>");
  2. compiled({epithet: "stooge"});
  3. => "Hello stooge"

If ERB-style delimiters aren’t your cup of tea, you can change Underscore’s template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML-escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. Note that if part of your template matches more than one of these regexes, the first will be applied by the following order of priority: (1) escape, (2) interpolate, (3) evaluate. You may define or omit any combination of the three. For example, to perform Mustache.js-style templating:

  1. _.templateSettings = {
  2. interpolate: /\{\{(.+?)\}\}/g
  3. };
  4. var template = _.template("Hello {{ name }}!");
  5. template({name: "Mustache"});
  6. => "Hello Mustache!"

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

  1. _.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
  2. => "Using 'with': no"

Precompiling your templates can be a big help when debugging errors you can’t reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The source property is available on the compiled template function for easy precompilation.

  1. <script>
  2. JST.project = <%= _.template(jstText).source %>;
  3. </script>