Basics of UnderscoreJS

Basics of UnderscoreJs

UnderscoreJs is a JavaScript Utility library. It provides a huge collection of functions that comes in handy for the development process. The main focus of this library is to build applications faster and increase the productivity.

UnderscoreJs Categories:

Underscore js functions are grouped into different categories.

  • Collections
  • Arrays
  • Functions
  • Objects
  • Utility
  • Chaining

Each of these category contains functions that makes working with those categories easier.

Note: To acess the library functions we must use the "_", like how we use $ to access the global jQuery in jquery.

Examples

filter Function under Collections

For this example let's assume a shopping website. The website shows items with categories and each items will have a unique id with which the item is identified. We can use the filter function as shown below to implement a filter feature.

var availableItems = [{
    CategoryId: 2,
    Category: 'Computer Components',
    Name: 'RAM'
}, {
    CategoryId: 2,
    Category: 'Computer Components',
    Name: 'HDD'
}, {
    CategoryId: 3,
    Category: 'Furniture',
    Name: 'Dining Table'
}];

var categoryIdsFromUser = [2];

var filteredItems = _.filter(availableItems, function(item) {

    for (var i=0; i<categoryIdsFromUser.length; i++) {
        if (item.CategoryId === categoryIdsFromUser[i]) {
            return item;
        }
    }

});


uniq function under Array

The uniq function can be used to remove duplicate values. This function also works with strings. You can also pass custom iterator function to identify uniq items(for identifying uniqness in objects).

var userIds = [1, 2, 3, 1, 5, 3, 4, 6, 2, 6, 'Foo', 'Bar', 'Foo'];
var uniqUserIds = _.uniq(userIds);
alert(uniqUserIds);

Apart from this Underscore Function's category provides with a lot's of functions which you may find it very useful. is* functions can be used to identify if a given value is array, object, NAN, undefined and so on.

Each of these categories will be explained in detail in seperate posts. If you have any doubts leave a comment.