Underscorejs JavaScript library by example

Apr 2, 2013 00:00 · 454 words · 3 minute read Programming JavaScript

Underscore is a JavaScript open source library that brings lots of functions. You can download the latest version of the library from underscorejs.org .

For each

You can go through an array and reach to each element that exist in it .

A functional style

var numbers = [1, 3, 4];
_.each(numbers, function (num) {
alert('functional :' + num);
});

Output :

functional : 1 
functional: 3 
functional: 4

Object oriental style

_(numbers).each(function (num) {
alert('oo :' + num);
});

Output :

oo : 1 
oo : 3 
oo : 4

In both ways in start with an “_” that followed by each method.

Mapping

You can map each element of an array to a new value.

var doubled = _(numbers).map(function (num) {
return num * 2;
});

To prove that it worked we can print the values of the new array.

_(doubled).each(function (num) { alert('mapped to double : ' + num); });

Output :

mapped to double : 2 
mapped to double :: 6 
mapped to double :: 8

Reduce

You can reduce an array to a single value .

var numbers = [1, 3, 4];
var reduced = _(numbers).reduce(function (single, num) { return single += num; }, 0);
alert(“reduced to single value : ” + reduced);

Output :

reduced to single value : 8

“single” is the output variable.

“num” is the element of our array

“{}” Is where you can put your business logic that how you want to convert your array element into a single variable.

Select

You can filter the variables of an array and select your desired output from it .

var filter = _(numbers).select(function (num) { return num % 2 === 0; });
alert("filter even numbers by select :" + filter[0]);

Output :

Filter even numbers by selecting : 4

The output of the select is an array and you can reach to the elements of it by using the index.

Check type

You can check the variable type of an array.

var numbers = [1, 3, 4];
var AreAllItemsNumber = _(numbers).all(function (item) { return typeof item === "number"; });
alert("Are all the items in number type : " + AreAllItemsNumber);

Output:

Are all the items in number type : true

Check existence

You can check if a number exists in an array or not.

var numbers = [1, 3, 4];
var isIncludeItem = _(numbers).include(3);
alert("is include item :" + isIncludeItem);

Output :

Is include item : true

Find max value

You can find the max value in an array.

var numbers = [1, 3, 4];
var maxValue = _(numbers).max();
alert(“max value is : ”+maxValue);

Output : max value is : 4

Download

Feel free to download the full source code of this example from my github.