Underscore

Underscore.js is an extension library for Javascript that provides more functionality with cross browser support.
Usually used along with jQuery and Backbone.js to help create the optimal website performance and clean code.

There are 80-odd functions which can be viewed at http://underscorejs.org

To include it in your html webpage just add
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>

Your functions need to start with “_.” for them to know to use the Underscore library.
If you run 2 functions on the same line then you can ignore the following “_”‘s and just use the dots “.”

I am going to run through a few I use regularly along with jQuery.
These examples can be view at: http://glynrob.com/examples/underscore/
No GitHub for this post as you can just view the source to see how everything works.

Utility

Template
This is the main feature I use.
This allows you to compile templates into functions for rendering.
All my examples use this feature to help keep my code cleaner.

<div class="page"></div>
<script type="text/template" id="title-template">
  <br class="clear" />
  <div class="row">
    <h3><%= header %></h3>
  </div>
</script>

<script>
  var template = _.template($('#title-template').html(), {header:'COLLECTIONS'});
  $('.page').append(template);
</script>

As you can see, I pass additional data into the template making it very easy for me to reuse this template in future

Mixin
Add your own functions to your arsenal by creating Mixins
My example only makes sure any string passed will capitalize the first character but you can do anything you wish here

Collections

Each
Shows an example of looping through an array and doing some action for each object within.
In this case just adding the age to another array.
var usersAges = new Array();
_.each(users, function(value, key, list){usersAges.push(value.age); });

Pluck
Allows you to easily pick out a specific property from an array or object
var usersAges = _.pluck(users, 'age');

Map
Creates a new array from a collection where values can be changed within a function
This example adds 1 to each record in the supplied array
var usersAgeNextYear = _.map(usersAges, function(num, key){ return num + 1; });

All
This loops through all items to see if every value passes a certain criteria.
In this case, if every user is below 60 then it will return true.
_(usersAgeNextYear).all(function (value){return value<60; });

FindWhere
Looks through the list and returns the first value that matches all of the key-value pairs.
Allot better than manually looping through all results.
_.findWhere(users, {name: "larry"});

Max
Returns the maximum value in list.
var maxAge = _.max(usersAgeNextYear);

Arrays

Range
Quickly create an array incremented by the number provided
Be careful of the max number in the range as it does not include the current value. If I chose 0, 30, 5 then the last 30 value would not be present.
_.range(0, 31, 5);
Returns: [0, 5, 10, 15, 20, 25, 30]

Flatten
Flattens a nested array
_.flatten([1, 50, 12, 0, [2], [3, [[4]]]]);
Returns: [1, 50, 12, 0, 2, 3, 4]

Compact
Returns a copy of the array with all false values removed.false, null, 0, “”, undefined and NaN are all false.
_.compact([0, 1, false, 2, '', 3]);
Returns: [1, 2, 3]

IndexOf
Returns the index at which value can be found in the array
This looks for the first instance of the value 10
_.indexOf([0, 1, 2, 10, 8, 9, 11, 4, 3], 10);
Returns: 3

Functions

Compose
Returns the composition of a list of functions, where each function consumes the return value of the function that follows.
This is an example of a payment system where the original charge is £12, then add delivery charges and finally add the additional tax.

var addDelivery = function(value){ return value + 5; };
var addTax = function(value){ return value*1.175; };
var calcCost = _.compose(addDelivery, addTax);
calcCost(12)

Memoize
Memoizes a given function by caching the computed result.
So when you have a large computation to do regularly you can cache the results to speed everything up.

var calculation = _.memoize(function(n) {
  return n * 100;
});
calculation(2)

Objects

Invert
Returns a copy of the object where the keys have become the values and the values the keys.
var inverted = _.invert({0:"Zero", 1:"One", 2:"Two", 3:"Three"});
Returns: [0, 1, 2, 3]

Pick
Return a copy of the object, filtered to only have values for the whitelisted keys
var picked = _.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
Returns: [“moe”, 50]

Omit
Return a copy of the object, filtered to omit the blacklisted keys
var omit = _.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
Returns: [“moe”, 50]

 

So these are just a few examples of the additional power you can now have in javascript with this library.

Leave a Reply

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