Playing with Underscore.js

In this tutorial I’m going to introduce to you a JavaScript Library called Underscore.js. It’s a library used to make your life easier as a Javascript developer. It has a bunch of different functions used for grouping, sorting, and mapping objects.

I’m learning underscore.js as I’m writing this so if you don’t understand something just Google it and enlightenment will be yours.

I recommend that you play with underscore.js on the console, it’s the best place to introduce yourself to a JavaScript library since you will immediately see the output of what you’re writing.

 

Difference

This returns the items in an array which exists on the first argument but does not exist on the second argument. Which means that its return value depends upon the order of the arguments.

var ar1 = [1, 2, 3, 4, 5, 6];
var ar2 = [2, 3, 7, 9, 10, 1];

_.difference(ar1, ar2); //returns [7, 9, 10]

This can also work with arrays composed of strings:

var amp1 = {'names' : ['wern', 'paul', 'falk']};
var amp2 = {'names' : ['w', 'fa', 'wern']};

_.difference(amp2.names, amp1.names); //returns ["w", "fa"]

 

Uniq

The uniq method removes all the duplicates in an object. I don’t know how many arguments it could take but I managed to get two in the example below:

var names1 = ['paul', 'joseph', 'mark', 'matthew']; var names2 = ['joshua', 'ahab', 'michael', 'mark', 'paul']; _.uniq(names1, names2); //returns: ["paul", "joseph",

"mark", "matthew"]

 

All

This is one of my favorites. What his does is to check if all the items in an object meets the criteria that you specify. In the example below we are checking if all the items in the array ar1 is a number:

var ar1 = [1, 2, 3, 4, 5, 6]; _.all(ar1, function(value){ return typeof value == 'number'; });

//returns true

However if we try to put a string and a boolean:

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.all(ar1, function(value){ return typeof value == 'number'; });     //returns false

One possible use case for this method is input validations.

 

Map

I’m not particularly where can I use this one but it looks pretty cool. What this does is to map values to the items in the object that you specify.

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.map(ar1, function(val){ return val + " awesome"; })

And so the output depends on what you specified in the function body. The code above appends the word awesome to every item in the object ar1.

 

Select

This works just like the select query in SQL if ever you have worked with databases before. This requires 2 arguments the first one is the object that you want to use as your data source and the second argument is the function which is equivalent to the actual query in SQL. What I did below is to select all the items in the array ar2 that is greater than 1.

var ar2 = [2, 3, 7, 9, 10, 1]; _.select(ar2, function(val){ return val > 1; })

//returns [2, 3, 7, 9, 10]

 

SortBy

This allows you to sort the items in your object any way you want. In the example below I sorted the array ar2 randomly.

var ar2 = [2, 3, 7, 9, 10, 1]; _.sortBy(ar2, function(val){ return Math.random(val); });

//returns items in ar2 in a random order

 

Rest

Returns all items in the object except the first one.

var x = [1,2,3,4];

_.rest(x); //returns [2, 3, 4] 

 

Initial

Returns all items in the  object except the last one.

var x = [1,2,3,4];

_.initial(x); //returns [1, 2, 3]

 

Find

Returns the first item in the object that matches the criteria that you specified.

var x = [1,2,3,4];

_.find(x, function(v){ return v > 3; }); //returns 4

 

Filter

Similar to select, I don’t really know the difference.

var x = [1,2,3,4];

_.filter(x, function(v){ return v > 2;}); //returns [3, 4]

 

Pluck

Plucks out the values associated with the key that you specify.

var anime = [{title: 'death note', main_char: 'light yagami'},   {title: 'pokemon', main_char : 'ash'}, {title: 'd-grayman' , main_char : 'allen walker'}]; _.pluck(anime, 'main_char');

//returns [light yagami, ash, allen walker]

 

Shuffle

Returns the items in an object in a random order.

var x = [1, 2, 3, 4];
_.shuffle(x);

 

Union

As the name suggests, this merges all the items in the objects that you specify as the argument. Duplicates are removed in the process which means that only unique items are returned by the method.

var x = [1, 2, 3, 4];
var y = [4, 88 , 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.union(x, y, z);  //returns [1, 2, 3, 4, 88, 9, 20, 5, 7, 22]

 

Intersection

Returns all the items which exists on all of the objects that you specify.

var x = [1, 2, 3, 4];
var y = [4, 88, 2, 1, 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.intersection(x, y, z); //returns [1, 2]

 

Range

Returns an array of numbers that are within the range that you specify. The usage of the arguments depends on the number of arguments that you specify. If you only specify a single argument it is assumed that the initial value will be 0 and the step will be 1. Remember that the array that is returned is always zero-indexed.

_.range(4); //returns [0, 1, 2, 3]

If you specified 2 arguments then it is assumed that the step is 1 and the first argument is the initial value and the second argument is the terminal value.

_.range(2, 10); //returns [2, 3, 4, 5, 6, 7, 8, 9]

If you specified 3 arguments the first argument is the initial value, the second argument is the terminal value, and the third argument is the step. You can make use of this to easily create a multiplication table of any number.

_.range(2, 20, 2); //returns [2, 4, 6, 8, 10, 12, 14, 16, 18]

 

bindAll

Binds functions into specific events in an object(elements). It’s like event-delegation in jQuery.

Since were doing things in the console and in an empty page, we first need to create the elements that we will be working on.

var spark = document.createElement('input'); //creates an input element
spark.setAttribute('type', 'button'); //set type to button
spark.setAttribute('value', 'spark'); //set value to spark
spark.setAttribute('id', 'spark'); //set id to spark

var body = document.getElementsByTagName('body')[0]; //select the html body tag
body.appendChild(spark); //inject the button into the dom

After creating the element and injecting it into the DOM we set the properties.

var spark_props = {
   name : 'spark boom',
   onClick : function(){ alert('name is:  ' + this.name); }
}

Remember that you can add any property any time you want.

spark_props.boom = 'kapow'

Or even modify existing ones.

spark_props.name = 'bam!!!'

Call the bindAll() method to bind all the properties together.

_.bindAll(spark_props);

Finally, bind the click event to the button using the onEvent method as its action.

$('#spark').bind('click', spark_props.onClick)

 

Once

Creates a clone of the function which can only be called once. One use case that I could think of is when submitting forms sometimes users tend to click on the Submit button multiple times.

var save = _.once(function_to_send_data_to_server);

 

Each

Pretty much like the .each() method in jQuery if you’ve ever used jQuery before. It is used to iterate through the items of the object that you specify.

_.each(['re','mi','fa'], function(va){
   console.log(va);
});
//outputs:
re
mi
fa

 

Functions

Returns an array of functions stored in the object that you specified. The example below returns all the functions associated with Backbone.js, the number of functions returned only shows how lightweight it is.

_.functions(Backbone); returns

["Collection", "History", "Model", "Router",

"View", "noConflict", "setDomLibrary", "sync", "wrapError"]

 

Times

Takes up two arguments the first one is the number of times you want to execute the given function which is the second argument. You can pretty much use this like the _.each method.

var anime = [{title: 'death note', main_char: 'light yagami'},  

{title: 'pokemon', main_char : 'ash'},

{title: 'd-grayman' , main_char : 'allen walker'}];

 

_.times(anime.length,

function(index){console.log(anime[index]['main_char']);})

 

//outputs:

light yagami

ash

allen walker

 

Result

Reminds me of the getters and setters _.result is pretty much like the getter method in every programming language but this time you can either get the value for a particular key or execute a particular function.

 

Conclusion

That’s it! You’ve learned how to use some of the useful methods in underscore.js that you can use in your projects. If you’re already using jQuery you can use underscore.js as an enhancement since they will work together just fine.

 

Resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s