Google News
logo
Underscore.js - Interview Questions
Explain some Utility Functions in Underscore.js?
noConflict _.noConflict()
Give control of the global _ variable back to its previous owner. Returns a reference to the Underscore object.
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)
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.
var stooge = {name: 'moe'};
stooge === _.identity(stooge);
=> true
 
constant _.constant(value)
Creates a function that returns the same value that is used as the argument of _.constant.
var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true
 
noop _.noop()
Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.
obj.initialize = _.noop;​
times _.times(n, iteratee, [context])
Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.
_.times(3, function(n){ genie.grantWishNumber(n); });​
random _.random(min, max)
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.
_.random(0, 100);
=> 42
 
mixin _.mixin(object)
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.
_.mixin({
  capitalize: function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"
 
uniqueId _.uniqueId([prefix])
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.
_.uniqueId('contact_');
=> 'contact_104'
 
escape _.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"
 
unescape _.unescape(string)
The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, &#x60; and &#x27; with their unescaped counterparts.
_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"
 
result _.result(object, property, [defaultValue])
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.
var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"
 
now _.now()
Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.
_.now();
=> 1392066795351
 
template _.template(templateString, [settings])
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.
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b>&lt;script&gt;</b>"
You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "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.
_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
=> "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.
<script>
  JST.project = <%= _.template(jstText).source %>;
</script>
Advertisement