Using Underscore.js in Node.js Apps

Posted by: Ravi Kiran , on 7/27/2015, in Category Node.js
Views: 41996
Abstract: Use underscore.js in Node.js apps to take advantage of handy underscore methods that make our experience of working with Node.js better

Underscore.js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more. If you are familiar with LINQ in C#, underscore.js brings most of the capabilities of LINQ to JavaScript.


Node.js is a platform for building server side applications using JavaScript. While designing REST APIs in Node.js that interact with NoSQL databases like MongoDB, we either get an object or, a collection of objects. In most of the scenarios, we may not want to send the same object in response to the API. The data has to be mapped to the structure of the Data Transfer Object (DTO) designed for the API. This transformation would take a lot of time and energy if we do it manually. Underscore.js provides a set of handy methods that makes our job easier. In this post, we will see how to use Underscore.js and where it fits in Node.js applications.

Note: If you are new to Node.js, check Node.js Tutorial Series - Getting Started

Adding Underscore to a Node.js project

Underscore.js can be added to a Node.js application using NPM. Following command installs the library:

> npm install underscore

Once added, underscore can be referred in any of the Node.js modules using the CommonJS syntax:

var _ = require(‘underscore’);

Now we can use the object underscore (_) to operate on objects, arrays and functions.

Using Underscore to ease manual work

Say we have a list of employees in our application and we want create REST APIs that uses this data to perform certain operations and return the result:

var employeesCollection = [

Now let us assume, we want to fetch names and designations of all employees. In general, if we need to perform such an operation, we use a for loop or, for each loop to iterate over items in the array, create an object for every entry and keep pushing the new objects into another array.

However the method provided by underscore reduces the effort involved in this task. Following snippet shows the usage of this method:, function (employee) {
    return {name:, designation: employee.designation};

Sometimes, while generating a report for the company, you may require only names of its employees. The _.pluck method plucks values of the specified property and constructs a new array using these values:

_.pluck(employeesCollection, "name");

Another example could be when we have to perform multiple operations on the same collection to build the desired result. Underscore.js provides _.chain method to keep chaining multiple operations and in the end we need to call _.value to extract result of the chain. Following snippet filters employees by designation and then maps each entry to a reduced object with two properties:

 .filter(function (employee) {
    return employee.designation === designation;
 .map(function (employee) {
    return {name:, id:};

Underscore also provides some useful methods to perform operations on objects like checking type, if a property exists, extending an object from one or more objects, to clone an object and more.

Say, we need to calculate bonus of the employee and send it along with other details. The property ‘bonus’ can be added to the employee using the _.extend method. This method adds the property if the object already doesn’t have and doesn’t replace the value if the property already exists in the object. Following snippet shows this:

function calculateBonus(id){
    var emp=_.find(employeesCollection, function (employee) {
        return === id;
    return _.extend(emp, {bonus: emp.salary * 0.1});

Underscore’s methods for functions allow associating a function to an object, wrap a function, delay execution of a function and more. Of these methods, I personally used the _.bind method a lot. This method binds a function with an object. When the function is called, it is executed in the context of the object bound with. Following is an example of the bind method:

function getStatement(){
    var message = + " is working as a " + this.designation + " at ABC Company.";
    return message;

getStatement = _.bind(getStatement, employee);

return getStatement();


As we saw, underscore.js comes with a list of handy methods that make our experience of working with JavaScript better. Check the official site for documentation of all methods and start using them in your Node.js apps.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!