How to Use Underscore.js in Web Application

Tarun Kumar Chatterjee
.Net – Technology Specialist
September 5, 2016
Rate this article
[Total: 0    Average: 0/5]

Underscore is an open source functional programming utility library for JavaScript. Underscore provides many useful functions for working with arrays or collections of JavaScript objects, including filtering, sorting and querying.

Underscore.JS is an useful JavaScript library for anyone familiar with the LINQ syntax. It is not a direct LINQ, but provides a very useful "LINQ-like" experience for anyone familiar with functional programming.

Using underscore is as simple as adding the JavaScript file to your project and referencing it on the page. Below is the command needs to run through package manager console to load underscore.js into the solution

PM> Install-Package underscore.js

Now let me show you few examples on basic usage of Underscore.js

First need to take the reference of Underscore.js in the project

<script src="Scripts/underscore.min.js"></script>

var data = [{name: ‘Tarun2’, age: 50},{name: ‘Tarun1’, age: 40}, {name: ‘Tarun3’, age: 60}];

Returns the maximum value in list:

JSON.stringify( _.max(data, function (val) { return val.age; }));

Returns the list sorted by name:

JSON.stringify(_.sortBy(data, ‘name’));

Filter the list:

JSON.stringify(_.where(data, { name: ‘Tarun1’, age: 40 }));

New array of values by mapping each value in list:

JSON.stringify([1, 2, 3], function(num){ return num * 3; }))

Output will be [3,6,9]

List of Unique value in the list:

JSON.stringify(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]))

Output will be: [1,2,3,101,10]

Hope this artifact will give you some basic ideas about the Underscore.js and its utility in the project. It will have lot of other functions, we can refer those from : link.

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
.Net – Technology Specialist
Rate this article
[Total: 0    Average: 0/5]
Tarun has been working in IT Industry for over 8+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in .Net windows/Web. more

Leave a comment