Beginners Guide To Underscore.JS

Introduction

 
First off, it’s a tiny and powerful library with a minified and gzipped size of 5.7kb. You can download the same. 
 
The open-source code is located here.
 
The library supports over a hundred functions, most of them are very useful and can really simplify our day-to-day work involving the usage of JavaScript.
 
Here’s the complete definition of underscore.js from the official site.
 
“Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders”.
 
The underscore.js functions can be used to perform or do something on the Collection, Array and Objects. Also it has other utility functions that we will see later.
 
Using Code
 
Note
 
The following demo code is based on the unit test code of underscore.js.
 
Now let us see the real use of underscore.js with some sample examples. Considering an example of applying underscore.js array functions, I will walk you through an example.
 
Below is the code snippet where we are performing various array operations such as finding index, unique elements, set operations like union, intersection, difference etc.
 
Here’s the code snippet for the same.
  1. <script type="text/javascript">    
  2.     var array = [1, 2, 3, 1, 2, 3];    
  3.     console.log('First Function');    
  4.     console.log('_.first(' + array + ', 2): ' + _.first(array, 2));    
  5.     
  6.     var kittens = [    
  7.       {    
  8.         kitten: 'Celery',    
  9.         cuteness: 8    
  10.     },     
  11.       {    
  12.         kitten: 'Juniper',    
  13.         cuteness: 10    
  14.     },    
  15.       {    
  16.         kitten: 'Spottis',    
  17.         cuteness: 10    
  18.     }];    
  19.     
  20.     console.log('Unique Function');    
  21.     varexpectedKittens = _.uniq(kittens, true'cuteness');    
  22.     console.log('Actual: ' + JSON.stringify(kittens));    
  23.     console.log('Result: ' + JSON.stringify(expectedKittens));    
  24.     
  25.     //returns elements starting at the given index    
  26.     console.log('Rest Function');    
  27.     var numbers1 = [1, 2, 3, 4];    
  28.     var after = _.rest(numbers1, 2);    
  29.     console.log('_.rest(' + numbers2 + ', 2): ' + after);    
  30.     
  31.     // returns all but the last n elements    
  32.     var numbers2 = [1, 2, 3, 4];    
  33.     var after = _.initial(numbers2, 2);    
  34.     console.log('Initial Function');    
  35.     console.log('_.initial(' + numbers2 + ', 2): ' + after);    
  36.     
  37.     // fetch the last n elements    
  38.     var numbers3 = [1, 2, 3, 4];    
  39.     var after = _.last(numbers3, 2);    
  40.     console.log('Last Function');    
  41.     console.log('_.last(' + numbers3 + ', 2): ' + after);    
  42.     
  43.     // range function    
  44.     console.log('Range Function');    
  45.     console.log('_.range(3, 10, 3): ' + _.range(3, 10, 3));    
  46.     console.log('_.range(12, 7, -2): ' + _.range(12, 7, -2));    
  47.     
  48.     // last index of element    
  49.     console.log('LastIndexOf Function');    
  50.     console.log('_.lastIndexOf([-1, 1, 2], 1): ' + _.lastIndexOf([-1, 1, 2], 1));    
  51.     
  52.     // index of element    
  53.     console.log('IndexOf Function');    
  54.     console.log('_.indexOf([1, 1, 2], 1): ' + _.indexOf([1, 1, 2], 1));    
  55.     
  56.     // difference of two arrays    
  57.     console.log('Difference Function');    
  58.     var result = _.difference([1, 2, 3], [2, 30, 40]);    
  59.     console.log(' _.difference([1, 2, 3], [2, 30, 40]): ' + result);    
  60.     
  61.     result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);    
  62.     console.log(' _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]): ' + result);    
  63.     
  64.     // union of two arrays    
  65.     console.log('Union Function');    
  66.     var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);    
  67.     console.log(' _.union([1, 2, 3], [2, 30, 1], [1, 40]): ' + result);    
  68.     
  69.     result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);    
  70.     console.log(' _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]): ' + result);    
  71.     
  72.     // intersection of two arrays    
  73.     console.log('Intersection Function');    
  74.     var result = _.intersection([2, 4, 3, 1], [1, 2, 3]);    
  75.     console.log(' _.intersection([2, 4, 3, 1], [1, 2, 3]): ' + result);    
  76.     
  77.     //without    
  78.     console.log('Without Function');    
  79.     var list = [1, 2, 1, 0, 3, 1, 4];    
  80.     console.log(' _.without([1, 2, 1, 0, 3, 1, 4], 0, 1): ' + _.without(list, 0, 1));    
  81. </script>   
 
code
 
Now let us see the underscore collection related functions. In the following example, you will be seeing the usage of collection functions for iterating, finding, sorting, partitioning, and grouping elements.
  1. <script type="text/javascript">    
  2.     console.log('Simple Iterator')    
  3.     var array = [1, 2, 3, 4];    
  4.     console.log('Given Array:' + array)    
  5.     _.each([1, 2, 3], function(num, i)    
  6.     {    
  7.         console.log(i);    
  8.     });    
  9.     
  10.     console.log('Find elements')    
  11.     var array = [1, 2, 3, 4];    
  12.     console.log('Given Array:' + array)    
  13.     _.find(array, function(n)    
  14.     {    
  15.         if (n > 2) console.log(n);    
  16.     });    
  17.     
  18.     console.log('Filter even numbers');    
  19.     var array = [1, 2, 3, 4, 5, 6];    
  20.     varevenObject =    
  21.     {    
  22.         one: 1,    
  23.         two: 2,    
  24.         three: 3    
  25.     };    
  26.     varisEven = function(num)    
  27.     {    
  28.         return num % 2 === 0;    
  29.     };    
  30.     
  31.     console.log('Given Array:' + array)    
  32.     console.log(_.filter(array, isEven));    
  33.     
  34.     console.log('Reject even numbers');    
  35.     var array = [1, 2, 3, 4, 5, 6];    
  36.     var odds = _.reject([1, 2, 3, 4, 5, 6], function(num)    
  37.      {    
  38.         return num % 2 === 0;    
  39.     });    
  40.     console.log('Given Array:' + array)    
  41.     console.log(odds);    
  42.     
  43.     console.log('Find where');    
  44.     var list = [    
  45.     {    
  46.         a: 1,    
  47.         b: 2    
  48.     },    
  49.     {    
  50.         a: 2,    
  51.         b: 2    
  52.     },    
  53.     {    
  54.         a: 1,    
  55.         b: 3    
  56.     },    
  57.     {    
  58.         a: 1,    
  59.         b: 4    
  60.     },     
  61.     {    
  62.         a: 2,    
  63.         b: 4    
  64.     }];    
  65.     var result = _.findWhere(list,    
  66.     {    
  67.         a: 1    
  68.     });    
  69.     console.log('Given Input:' + JSON.stringify(list));    
  70.     console.log(result);    
  71.     
  72.     console.log('Max number');    
  73.     var array = [1, 2, 3, 4, 5, 6];    
  74.     var result = _.max(array);    
  75.     console.log('Given Array:' + array)    
  76.     console.log('Max:' + result);    
  77.     
  78.     console.log('Min number');    
  79.     var array = [1, 2, 3, 4, 5, 6];    
  80.     var result = _.min(array);    
  81.     console.log('Given Array:' + array)    
  82.     console.log('Min:' + result);    
  83.     
  84.     console.log('Sort By Age')    
  85.     var people = [{    
  86.         name: 'curly',    
  87.         age: 50    
  88.     }, {    
  89.         name: 'moe',    
  90.         age: 30    
  91.     }];    
  92.     console.log('Given Object:' + JSON.stringify(people))    
  93.     people = _.sortBy(people, function(person)    
  94.     {    
  95.         return person.age;    
  96.     });    
  97.     console.log('Result:' + JSON.stringify(people));    
  98.     
  99.     console.log('Group items')    
  100.     var array = [1, 2, 3, 4, 5, 6];    
  101.     var result = _.groupBy([1, 2, 3, 4, 5, 6], function(num)    
  102.      {    
  103.         return num % 2;    
  104.     });    
  105.     console.log('Result:' + JSON.stringify(result));    
  106.     
  107.     console.log('Group items by length')    
  108.     var list = ['one''two''three''four''five''six''seven''eight''nine''ten'];    
  109.     console.log('Given List:' + JSON.stringify(list));    
  110.     var grouped = _.groupBy(list, 'length');    
  111.     console.log(grouped['1']);    
  112.     console.log(grouped['2']);    
  113.     console.log(grouped['3']);    
  114.     console.log(grouped['4']);    
  115.     console.log(grouped['5']);    
  116.     
  117.     console.log('Count items by length')    
  118.     var grouped = _.countBy(list, 'length');    
  119.     console.log('Given List:' + JSON.stringify(list));    
  120.     console.log(grouped['3'], 4);    
  121.     console.log(grouped['4'], 3);    
  122.     console.log(grouped['5'], 3);    
  123.     
  124.     console.log('Partition items where element value < 4')    
  125.     var list = [0, 1, 2, 3, 4, 5];    
  126.     console.log('Given List:' + list);    
  127.     var result = _.partition(list, function(x)    
  128.     {    
  129.         return x < 4;    
  130.     });    
  131.     console.log('Result:' + JSON.stringify(result));    
  132. </script> 
 
code
 
Let us take a look into the underscore.js object function usages.
  1. <script type="text/javascript">    
  2.     console.log('Keys function');    
  3.     varobj = {    
  4.         one: 1,    
  5.         two: 2    
  6.     };    
  7.     console.log('Given Object:' + JSON.stringify(obj))    
  8.     console.log('Result: ' + JSON.stringify(_.keys(obj)));    
  9.     
  10.     console.log('Values function');    
  11.     varobj = {    
  12.         one: 1,    
  13.         two: 2    
  14.     };    
  15.     console.log('Given Object:' + JSON.stringify(obj))    
  16.     console.log('Result: ' + JSON.stringify(_.values(obj)));    
  17.     
  18.     console.log('Pairs function');    
  19.     varobj = {    
  20.         one: 1,    
  21.         two: 2,    
  22.         three: 3    
  23.     };    
  24.     console.log('Given Object:' + JSON.stringify(obj))    
  25.     console.log('Result: ' + JSON.stringify(_.pairs(obj)));    
  26.     
  27.     console.log('Invert function');    
  28.     varobj = {    
  29.         cat: 1,    
  30.         dog: 2,    
  31.         pig: 3    
  32.     };    
  33.     console.log('Given Object:' + JSON.stringify(obj))    
  34.     console.log('Result: ' + JSON.stringify(_.invert(obj)));    
  35.     
  36.     console.log('Pick function');    
  37.     varobj = {    
  38.         cat: 1,    
  39.         dog: 2,    
  40.         pig: 3    
  41.     };    
  42.     console.log('Given Object:' + JSON.stringify(obj))    
  43.     console.log('Result: ' + JSON.stringify(_.pick(obj, 'cat')));    
  44.     
  45.     console.log('Omit function');    
  46.     varobj = {    
  47.         cat: 1,    
  48.         dog: 2,    
  49.         pig: 3    
  50.     };    
  51.     console.log('Given Object:' + JSON.stringify(obj))    
  52.     console.log('Result: ' + JSON.stringify(_.omit(obj, 'cat')));    
  53.     
  54.     console.log('Clone function');    
  55.     varobj = {    
  56.         cat: 1,    
  57.         dog: 2    
  58.     };    
  59.     var clone = _.clone(obj);    
  60.     console.log('Given Object:' + JSON.stringify(obj))    
  61.     console.log('Cloned Object:' + JSON.stringify(clone))    
  62.     
  63.     console.log('Has function');    
  64.     varobj = {    
  65.         cat: 1,    
  66.         dog: 2    
  67.     };    
  68.     console.log('Given Object:' + JSON.stringify(obj))    
  69.     console.log('Result:' + _.has(obj, 'cat'))    
  70.     
  71.     console.log('IsDate function');    
  72.     vardt = new Date();    
  73.     console.log('_.isDate(' + dt + '): ' + _.isDate(dt));    
  74.     
  75.     console.log('IsFinite function');    
  76.     console.log('_.isFinite(NaN): ' + _.isFinite(NaN));    
  77.     console.log('_.isFinite(1): ' + _.isFinite(1));    
  78.     
  79.     console.log('IsFunction function');    
  80.     console.log('_.isFunction([1, 2, 3]): ' + _.isFunction([1, 2, 3]));    
  81.     console.log('_.isFunction(function(){}): ' +    
  82.         _.isFunction(function() {}));    
  83.     
  84.     console.log('IsBoolean function');    
  85.     console.log('_.isBoolean(1): ' + _.isFinite(1));    
  86.     console.log('_.isBoolean(test): ' + _.isFinite('test'));    
  87.     
  88.     console.log('IsNumber function');    
  89.     console.log('_.isNumber(1): ' + _.isNumber(1));    
  90.     console.log('_.isNumber(NaN): ' + _.isNumber(NaN));    
  91.     
  92.     console.log('IsString function');    
  93.     console.log('_.isString(1): ' + _.isString(1));    
  94.     console.log('_.isString(testing): ' + _.isString('testing'));    
  95.     
  96.     console.log('IsArray function');    
  97.     console.log('_.isArray([1, 2, 3]): ' + _.isArray([1, 2, 3]));    
  98.     
  99.     console.log('IsObject function');    
  100.     console.log('_.isObject(new String(string): ' + _.isObject(new String('string')));    
  101.     console.log('_.isObject(12): ' + _.isObject(12));    
  102.     
  103.     console.log('IsEmpty function');    
  104.     varargs = function() {    
  105.         return arguments;    
  106.     };    
  107.     // empty arguments object is empty    
  108.     console.log('_.isEmpty(args()): ' + _.isEmpty(args()));    
  109.     console.log('_.isEmpty(""): ' + _.isEmpty(''));    
  110.     console.log('_.isEmpty(null): ' + _.isEmpty(null));    
  111.     
  112.     console.log('IsEqual function');    
  113.     var a = [{    
  114.         abc: null    
  115.     }];    
  116.     var b = [{    
  117.         abc: null    
  118.     }];    
  119.     console.log('_.isEqual(a, b):' + _.isEqual(a, b));    
  120. </script>   
 
code
 
Now let us try to understand the underscore.js template usage. The template allows one to easily insert HTML code on the fly. The underscore has a template function and allows us to run the template with the data. It is helpful when you wish to perform dynamic data loading.
 
You can extract a reusable or repetitive code and make it a template. The underscore template is easy to use and powerful. Below is the code snippet that explains the usage of _.template underscore function.
 
Let us define our HTML document to display a table with some data.
  1. <html>    
  2.     
  3. <head>    
  4.     <script type="text/javascript" src="http://underscorejs.org/underscore-min.js">    
  5.     </script>    
  6.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    
  7.     </script>    
  8. </head>    
  9.     
  10. <body>    
  11.     <table class="outer">    
  12.         <thead>    
  13.             <tr>    
  14.                 <th>Id</th>    
  15.                 <th>Website</th>    
  16.             </tr>    
  17.         </thead>    
  18.         <tbody>    
  19.         </tbody>    
  20.     </table>    
  21. </body>    
  22.     
  23. </html>   
Now, let us define the template. Below is the code snippet for the same. Note – We should not forget to specify the script block with “text/html”.
 
From the below code, we are iterating through the “items”, for each item, we will be creating a table row <tr> with two columns, one to show the “Id” and the other to display the website name.
  1. <script type="text/html" id='table-data'>    
  2.     <% _.each(items,function(item,key,list){ %>    
  3.         <tr>    
  4.             <td>    
  5.                 <%= key %>    
  6.             </td>    
  7.             <td>    
  8.                 <%= item.name %>    
  9.             </td>    
  10.         </tr>    
  11.         <% }) %>    
  12. </script>   
Let us code a script block to run the above template. Here’s the code snippet. You can see below, we have defined the items to display. The first thing we have to do is, get the table template to display. So we can run the template by making a call to _.template, passing in the template and items. The underscore.js runs the template with the data and returns HTML.
  1. <script type="text/javascript">    
  2.     var items = [    
  3.       {    
  4.         name: "CsharpCorner"    
  5.     },     
  6.       {    
  7.         name: "CodeProject"    
  8.     },     
  9.       {    
  10.         name: "StackOverFlow"    
  11.     }];    
  12.     
  13.     vartableTemplate = $("#table-data").html();    
  14.     
  15.     $("table.outertbody").html(_.template(tableTemplate,    
  16.     {    
  17.         items: items    
  18.     }));    
  19. </script>   
 
code
 
More information and explanation of underscore.js functions can be read.
 
Read more articles on JavaScript: