JavaScript: Node & UnderscoreJs

(Last Updated On: )

In this tutorial we will be giving out some quick examples of underscore.js functionality. To know more go here. There are so many to choose such as arrays, collections, objects, etc.

Q: What is underscore.js you ask?
A: It is a JavaScript library which provides utility functions for common programming tasks.

First thing we need to do is install it. You will need a node site already ready to go. If you don’t have one you can follow this tutorial on setting a basic one up.

npm install underscore --save

On whatever page you are working with all you need to do is add the following to where your requires are.

var _ = require('underscore');

Now we can use the functionality as we wish. I will do some basic uses below.

Array first:

Let’s say we want to get the first item in an array. This would return “456”.

_.first([456,6,32,11,99])
Array uniq:

If you want to trim out the duplicates in an array. This would return “456 6 32 11 99 89 45”.

_.uniq([456, 6, 32, 11, 99, 6, 89, 99, 45])
Collections contains:

If you want to check that a collection has a value. This will return “false” because 3 is not in the collection.

_.contains([4,5,6], 3)