Home » Underscore » Underscore Objects and Utility

Underscore Objects and Utility

Welcome to the forth and the last module of Undersore.js tutorial. In this Module we will cover some basic concepts of underscore object and utility function.

So let’s go through each of the utility function one by one.

 

_.keys(object) 
_.keys() function retrieves all the keys.

var objectKeys = _.keys(objectArray[1]);
console.log(objectKeys);

// console: ["name", "age"]

 

_.values(object) 
_.values() function retrieves all the values.

var objectValue = _.values(objectArray[1]);
console.log(objectValue);

// console: ["John", 23]

 

_.pairs(object) 
_.pairs() function returns [key, value] pair.

var objectPair = _.pairs(objectArray[1]);
console.log(objectPair);

// console: [["name", "John"], ["age", 23]]

 

_.invert(object)
_.invert() function inverts key to value and value to key.

var objectInvert = _.invert(objectArray[1]); // inverts key -> value and value -> key
console.log(objectInvert);

// console: {23: "age", John: "name"}

 

_.extend(destination, *sources)
_.extend() function copies all the keys and values from sources to destination object.
It overrides the property value if it’s already in destination.

var extendPersonAge = _.extend(objectArray[1],{country:"India", sex:"male", age:25});
console.log(extendPersonAge);

// console: name: "John", age: 25, country: "India", sex: "male"

In “objectArray” John’s age is 23 but in source we are passing 25, so it overrides the existing value of age property.

 

_.pick(object, *keys)
_.pick() function returns key and value of white-listed key.
we can pass multiple keys separated by comma.

var pickAge = _.pick(objectArray[1], 'age');
console.log(pickAge);

// console: age: 25

 

_.omit(object, *keys)
_.omit() function removes key and value of blacklisted key.
we can pass multiple keys to _.omit() function separated by comma.

var omitAge = _.omit(objectArray[1], 'age');
console.log(omitAge);

// console: {name: "John", country: "India", sex: "male"}

 

_.defaults(object, *defaults)
_.defaults() function adds the default value for undefined properties only.

var defaultValue = _.defaults(objectArray[1], {country:"India", age:43});
console.log(defaultValue);

// console: {name: "John", age: 25, country: "India", sex: "male"}

Will add default value for country; age will remain same( because it is already defined in objectArray).

 

_.tap
_.tap() function is used to tap (intercept) and return intermediate result.
Its usage will be explained in chain utility function.

 

_.has(object, key)
Check if the object has the given key.
Returns true if the object has key or else returns false.

var hasAge = _.has(objectArray[1], 'age');
console.log(hasAge);

// console: true

 

_.is* function
Underscore provides number of is* functions, these functions return Boolean value.
We will not cover these functions in this tutorial, they are pretty straight forward to understand.
For further reference please refer Undersore.js official site.

 

UTILITY Functions

_.times(n, iterator, [context])
_.times() function calls iterator function n number of times.

var timesFunction = _.times(10, function(e){
   return e*e;
});
console.log(timesFunction);

// console: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81

 

_.random(min, max)
_.random() function returns random number between min and max value.

var randomInteger = _.random(0,2);
console.log(randomInteger);

// console: 2

It returns one random value, this value can be min value or a max value i.e. value can any one from  0,1,2 in above example.

 

_.mixin(object)
_.mixin() function is one of the most important utility function of this library, it allows a user to extend underscore to have own function and implementation.

_.mixin({
takeInput:function(numberA, numberB){ // user defined function
   this.sum(numberA, numberB);
   this.minus(numberA, numberB);
   this.multiplication(numberA, numberB);
   this.division(numberA, numberB);
},
sum:function(a,b){
   console.log("sum "+ (a+b));
},
minus:function(a,b){
   console.log("subtraction "+ (a-b));
},
multiplication:function(a,b){
   console.log("multiplication "+ (a*b));
},
division:function(a,b){
   console.log("division "+ (a/b));
}
});

var mathOpertation = _.takeInput(6,3); // calling the user defined function

// console: sum 9 ; subtraction 3 ; multiplication 18 ; division 2

This function will be added to underscore library for that instance.
To check this we will make use of _.function().

_.function(object) returns name of all the functions within that object.

So after executing above code, write:

 _.function(_) //in console

You will get the list of all the underscore functions which will have names of all the native underscore functions + user defined functions (i.e. takeInput in this case).

 

_.escape(string)
_.escape() function Escapes a string for insertion into HTML, replacing &, <, >, “, ‘, and / characters. (From undersocre.js website)

var escapedHeading = _.escape('<h1> This is heading tag </h1>');
console.log(escapedHeading);

// console: &lt;h1&gt; This is heading tag &lt;/h1&gt;

 

_.unescape(string)
_.unescape() function is the opposite of _.escape() function, this function replaces &amp;, &lt;, &gt;, &quot;, &#x27;, and &#x2F; with their unescaped counterparts.

var unescapedHeading = _.unescape(' &lt;h1&gt; This is heading tag &lt;/h1&gt; ');
console.log(unescapedHeading);

// console: <h1> This is heading tag </h1>

 

_.result(object, property)
_.result() function returns either the value of property or executes the function and return its value.

var data = {firstName: 'Himanshu',lastName: 'Chahar', country:'India', fullName:function(){ return this.firstName+" "+this.lastName}};
console.log(_.result(data, 'country'));
console.log(_.result(data, 'fullName'));

// console: India
// console: Himanshu Chahar

 

_.chain(obj)
_.chain() function allows us to chain multiple underscore functions and give final result.
To stop the chain and return final result we should call _.value() function.

var sumOfAge = _.chain(objectArray).
    pluck('age').
    tap(function(){ console.log("break-point") }). // tap function used as an interceptor
    reduce(function(memo, number){ return memo+number }).
    value();

console.log(sumOfAge);

// console: break-point
// console: 164

 

_.template(templateString, [data], [settings])
Underscore provides _.template() function to render HTML.
Let’s start with simple implementation of _.template() function.

 

Simple Template:

var person = {name:'Himanshu', age:26}

var temp = _.template('Name is <%=name%>, age is <%=age%>',person);
console.log(temp);

// console: Name is Himanshu, age is 26

In the above example I am binding person object with template. You will notice that to display the variable value within the template i am using ”<%= %>” ,this is used to interpolate variable.

 

Passing object array and displaying list:

var personTemplate = _.template('<ul>'+
              '<%_.each(objectArray,function(e){%>'+ 
              '<li><%=e.name%> : <%=e.age%></li>'+
              '<%})%>'+'</ul>');

console.log(personTemplate());
document.getElementById('id_personList').innerHTML = personTemplate(); // display list on screen

//console: <ul><li>Himanshu : 26</li><li>John : 23</li><li>Sarah : 28</li><li>Steve : 33</li><li>Bosco : 26</li><li>Piyush : 28</li></ul>

Above example will display list in browser. You will notice, to interpolate JS code i am using ”<% %>”

We can interpolate escaped HTML value also by using “<%- %>”

 

User defined delimiter
There can be scenarios where you may want to use your own delimiter instead of using HTML’s predefined tags. Underscore provides you the privilege to do that.
There are two ways to achieve that:

  • 1st setting delimiter using _.template Settings:
_.templateSettings = {
          interpolate: /..Codeureka(.+?)Codeureka../g
};

var compiled = _.template('Name is ..Codeureka name Codeureka.., age is ..Codeureka age Codeureka..',person);
console.log(compiled);

// console: Name is Himanshu, age is 26

In above example i am using “Codeureka” as my delimiter. “..Codeureka” is starting tag and “Codeureka..” is ending tag.
And

  • 2nd passing delimiter as a template settings:
var tempSetting = {
        interpolate: /..Codeureka(.+?)Codeureka../g
};

var compiled = _.template('Name is ..Codeureka name Codeureka.., age is ..Codeureka age Codeureka..',person);
console.log(compiled);

// console: Name is Himanshu, age is 26

In second approach i have created a variable “tempSetting” and passing it as a setting parameter to _.template

 

Local Variable:
_.template() function can also be used to improve the performance by changing the scope. By default, underscore uses the JS “with” statement, which sets the passed data object as the default object for template.
Now to enhance the performance you can change the scope by passing the variable as a setting parameter in _.template() function, in that way the passed variable will bind as a default object with the template (using JS “with” statement).

var templateScope = _.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'});
console.log(templateScope);

// console: "Using 'with': no"

I have taken this example from Underscore website, here “data” is passed as a variable which will bind as a default object for the template.

 

So finally we have come to an end of this series, we have tried to cover almost all the major concepts that you need to create an application using Underscore.js library. Please comment and let us know if you have any suggestion or if you want us to include more topics.

Thanks!!! Happy CoDing…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>