Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted February 12th, 2016
Underscore.js

Did you ever look at your JavaScript code and though: “Shouldn’t it be easier than this”. Well with Underscore.js you can! Underscore is a JavaScript library with a lot of useful functions.

Installation Methods

nodejs / npm

$ npm install underscore

bower

$ bower install underscore

Underscore in action

Example: You only want the students with a minimum score of 6.

It would look like this:

var students = [{name: 'John', score: 8}, {name: 'Joe', score: 4}, {name: 'Jane', score: 6}],
    minimumScore = 6,
    topStudents = [];

for (i = 0; i < students.length; i++) {
    if (students[i].score >= minimumScore) {
        topStudents.push(students[i]);
    }
}

console.log(topStudents);
// output: [{name: 'John', score: 8}, {name: 'Jane', score: 6}]

Let’s take a look at Underscore:

var students = [{name: 'John', score: 8}, {name: 'Joe', score: 4}, {name: 'Jane', score: 6}],
    minimumScore = 6,
    topStudents = [];

topStudents = _.filter(students, function (student) {
    return student.score >= minimumScore;
});

console.log(topStudents);
// output: [{name: 'John', score: 8}, {name: 'Jane', score: 6}]

Wow that was easy and incredibly readable!

Functional or Object Oriented?

In the example above I used the functional approach. Example of the functional approach:

topStudents = _.filter(students, function (student) {
    return student.score >= minimumScore;
});

But we also can write it object oriented, like this:

topStudents = _(students).filter(function (student) {
    return student.score >= minimumScore;
});

Did you notice the slight diffrence?

What about it’s functionality?

Underscore provides a lot of functionality. The groups of functionality are:

  • Collections
  • Arrays
  • Functions
  • Objects
  • Utility
  • Chaining

I’ll show you some examples of each group.

Collections

Pluck

Extracting a list of property values.

So we i.e. we want all the names of our students. That will be a piece of cake!

var students = [{name: 'Bob', age: 16}, {name: 'Jane', age: 17}, {name: 'Joe', age: 15}];
var names = _(students).pluck('name');
console.log(names);
// output: ["Bob", "Jane", "Joe"]

Max

Returns the maximum value in list.

So who is the oldest of all students?

var students = [{name: 'Bob', age: 16}, {name: 'Jane', age: 17}, {name: 'Joe', age: 15}];
var oldest = _(students).max(function (student) {
    return student.age;
});
console.log(oldest);
// output: {name: "Jane", age: 17}

Arrays

Uniq

Filters the duplicates.

var numbers = [1, 2, 1, 4, 1, 3, 5, 9, 7, 2, 5, 4, 9, 5, 7];
var uniqueNumbers = _(numbers).uniq();
console.log(uniqueNumbers);
// output: [1, 2, 4, 3, 5, 9, 7]

Range

Creates a range of numbers.

console.log(_.range(0, 100, 10));
// output: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
console.log(_.range(10));
// output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Functions

Once

Creates a version of the function that can only be called one time.

var init = _.once(function () {
    console.log('Called!');
});
init();
// output: "Called!"
init();
// output: <no output>

Objects

Keys

Retrieve all the names of the object’s own enumerable properties.

var keys = _.keys({one: 1, two: 2, three: 3});
console.log(keys);
// ["one", "two", "three"]

Utility

Template

Rendering complicated bits of HTML from JSON data sources.

var data = {name: 'Boraida'},
    parser = _.template('Hello! My name is < %= name %> :-)');

console.log(parser(data));
// output: "Hello! My name is Boraida :-)"
console.log(parser({name: 'Jane'}));
// output: "Hello! My name is Jane :-)"

Chaining

Returns a wrapped object.
Calling methods on this object will continue to return wrapped objects until value is called.

var students = [{name: 'John', score: 8}, {name: 'Joe', score: 4}, {name: 'Jane', score: 6}];
var names = _(students).chain()
                .pluck('name')
                .sort()
                .value();

console.log(names);
// output: ["Jane", "Joe", "John"]

The End

I really like to work with Underscore.js because of it’s easy to use and very readable. All those crazy big for loops with if-statements are not needed anymore with this library :-)!

Well that’s it for now and thank you for reading!

Posted by Boraida Al-Assbahi

Leave a Reply

Your email address will not be published. Required fields are marked *