Wednesday, December 7, 2016

Underscore.js : The Best Developer Productivity Tool

If you are dealing with JavaScript/Json Objects or Arrays or Collections in your project, Underscore.js would be the best developer productivity tool. It has more than 80 + in-built utility functions to perform various operations on Javascript Objects.

At first glance, you may think that JQuery library and Underscore.js has similar functionality but JQuery library mainly concentrate on DOM manipulation whereas Underscore.js offers only utility functions to manipulate Javascript Objects.

Underscore.js offers more control on Javascript Object compare to JQuery
The file size of Underscore.js is less than 5.9 KB after compression and GZip.

You can download minimized Underscore.js from http://underscorejs.org/underscore-min.js
You can download complete utility functions from http://underscorejs.org/

Few popular utility functions

1.    pluck
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
Output : ["moe", "larry", "curly"]

2. find
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
Output: 2

3. filter
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
Output: [2, 4, 6]

4. min
var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
Output : 2

5. sortBy
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
Output: [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

6. countBy
_.countBy([1, 2, 3, 4, 5], function(num) {return num % 2 == 0 ? 'even': 'odd';});
Output : {odd: 3, even: 2}

Happy Coding :)

No comments:

Post a Comment