Underscore(_) JS & It’s Data Functions

What is Underscore? (Introduction)

Underscore is a JavaScript library for working with data and It makes it quite easy to perform common operations on data that you will run into over and over again If you’re building web application that needs to consume data from the internet. Underscore works on JavaScript JSON Objects Arrays etc essentially any correction of data that you have in your JavaScript application you can use underscore to manipulate it. Underscore contains a wide variety of very useful data related functions for doing all kinds of operation on data and we’ll get more into that in just a moment.

Can we use other Libraries like jQuery?

The great thing about underscore is that it can be used with other libraries jQuery. For example jQuery is really a great at manipulating the Dom and the contents of WebPages underscore is really a great at manipulating data so you might use underscore to manipulate the data when jQuery lay out the data in a web page. Using jQuery with underscore is a very powerful combination so if you’re using already jQuery I really strongly suggest that you look into underscore for your data needs.

What kind of Data Related operations can we do with Underscore? (Features of Underscore):

  • Can create data sets small and large. Also create small data sets from larger one.
  • Depends upon various criteria data can be sort and grouped.
  • Data can be transformed into different shapes and formats.
  • Can derive new data from existing data and extend datasets with new properties.
  • Can format data using templates.

CDN to use Underscore JS

Here is the CDN for the underscore JS. This link must be included with the web page to use underscore JS functions.


Underscore Functions

There are approx 80-100 functions inside the underscore JS library. Some of those functions are defined below.

Array Functions:

1. First:- _.first (array, [n])

Returns the first element of the passing array.

_.first ([8,5,6,9,4]); // 8

2. Compact:- _.compact(array)

Returns an array with removed all false values.

_.compact([2,false,7,0,6,’’]); // [2,7,6]

Object Functions:

1. Keys:- _.keys(object)

Return all the keys of the passing object.

_.keys ({one: 1,two: 2,three: 3}); // [“one”, ”two”, ”three”]

2. Values:- _.values(object)

Return all the values of the passing object.

_.values ({one: 1,two: 2,three: 3}); // [1,2,3]

Collection Functions:

1. Each:- This is just like the FOR loop.

var employees = [“Rick”, “John”, “Smith”];
_each (employees, function (employee, index, employees){
// Rick, John, Smith

2. Map:- Produced an new array by mapping each value in array.
_.map([2, 4,6],function(num){ return num*2;});//[4,8,12]

_.map({one: 1,two: 2,three: 3},function(num){ return num*2;});//[3,6,9]

There are lots of more in Underscore JS which can’t possible to add here. So for more detail go through this link Underscore.js

Leave a comment