Underscore.JS - Quick Guide



Underscore.JS - Overview

Underscore.JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on. Underscore.JS can be used directly inside a browser and also with Node.js.

Working with objects using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with them. Underscore comes with lots of features that eases your work with objects.

Underscore.JS is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js.

Features

Let us understand in detail all the important features available with Underscore −

Collections

Underscore.JS provides various functions for collections like each, map, reduce which are used to apply an operation on each item of a collection. It provides method like groupBy, countBy, max, min which processes collections and ease lot of tasks.

Arrays

Underscore.JS provides various functions for arrays like to iterate and process arrays like first, initial, lastIndexOf, intersection, difference etc.

Functions

Underscore.JS provides functions such as bind, delay, before, after etc.

Objects

Underscore.JS provides functions to manipulate objects, to map objects and comparing objects. For example, keys, values, extends, extendsOwn, isEqual, isEmpty etc.

Utilities

Underscore.JS provides various utilities methods like noConflict, random, iteratee, escape etc.

Chaining

Underscore.JS provides chaining methods as well like chain, value.

In subsequent chapters, we'll cover importants functions of Underscore.JS

Underscore.JS - Environment Setup

In this chapter, you will learn in detail about setting up the working environment of Underscore.JS on your local computer. Before you begin with working on Underscore.JS, you need to have the access to the library. You can access its files in any of the following methods −

Method 1: Using Underscore.JS File in Browser

In this method, we are going to need Underscore.JS file from its official website and will use it directly in the browser.

Step 1

As a first step, go to the official website of Underscore.JS https://underscorejs.org/.

Observe that there is a download option available which gives you the latest underscore-min.js file UMD (Production) available. Right Click on the link and choose save as. Note that the file is available with and without minification.

Step 2

Now, include underscore-min.js inside the script tag and start working with Underscore.JS. For this, you can use the code given below −

<script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>

Given here is a working example and its output for a better understanding −

Example

<html>
   <head>
      <title>Underscore.JS - Working Example</title>
      <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
      <style>
         div {
            border: solid 1px #ccc;
            padding:10px;
            font-family: "Segoe UI",Arial,sans-serif;
            width: 50%;
         }
      </style>
   </head>
   <body>
      <div style = "font-size:25px" id = "list">
	  </div>
      <script type = "text/JavaScript">
         var numbers = [1, 2, 3, 4];
         var listOfNumbers = '';
         _.each(numbers, function(x) { listOfNumbers += x + ' ' });
         document.getElementById("list").innerHTML = listOfNumbers;
      </script>
   </body>
</html>

Output

Method 2: Using Node.js

If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install Underscore.JS −

npm install underscore

You can observe the following output once Underscore.JS is successfully installed −

+ underscore@1.10.2
added 1 package from 1 contributor and audited 1 package in 6.331s
found 0 vulnerabilities

Now, to test if Underscore.JS works fine with Node.js, create the file tester.js and add the following code to it −

var _ = require('underscore');
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';
_.each(numbers, function(x) { listOfNumbers += x + ' ' });
console.log(listOfNumbers);

Save the above program in tester.js. The following commands are used to compile and execute this program.

Command

\>node tester.js

Output

1 2 3 4

Underscore.JS - Iterating Collections

Underscore.JS has many easy to use methods which helps in iterating Collections. This chapter discusses them in detail.

Underscore.JS provides various methods to iterate the Collections as listed below −

Sr.No. Method & Syntax
1 each

_.each(list, iteratee, [context])

2 map

_.map(list, iteratee, [context])

3 reduce

_.reduce(list, iteratee, [memo], [context])

4 reduceRight

_.reduceRight(list, iteratee, [memo], [context])

5 find

_.find(list, predicate, [context])

6 filter

_.filter(list, predicate, [context])

7 where

_.where(list, properties)

8 findWhere

_.findWhere(list, properties)

9 reject

_.reject(list, predicate, [context])

10 every

_.every(list, [predicate], [context])

11 some

_.some(list, [predicate], [context])

Underscore.JS - Processing Collections

Underscore.JS has many easy to use methods which helps in processing Collections. This chapter discusses them in detail.

Underscore.JS provides various methods to process the Collections as listed below −

Sr.No. Method & Syntax
1 contains

_.contains(list, value, [fromIndex])

2 invoke

_.invoke(list, methodName, *arguments)

3 pluck

_.pluck(list, propertyName)

4 max

_.max(list, [iteratee], [context])

5 min

_.min(list, [iteratee], [context])

6 sortBy

_.sortBy(list, iteratee, [context])

7 groupBy

_.groupBy(list, iteratee, [context])

8 indexBy

_.indexBy(list, iteratee, [context])

9 countBy

_.countBy(list, iteratee, [context])

10 shuffle

_.shuffle(list)

11 sample

_.sample(list, [n])

12 toArray

_.toArray(list)

13 size

_.size(list)

14 partition

_.partition(list, predicate)

15 compact

_.compact(list)

Underscore.JS - Iterating Array

Underscore.JS has many easy to use methods which helps in iterating Arrays. This chapter discusses them in detail.

Underscore.JS provides various methods to iterate the Arrays as listed below −

Sr.No. Method & Syntax
1 first

_.first(array, [n])

2 initial

_.initial(array, [n])

3 last

_.last(array, [n])

4 rest

_.rest(array, [index])

5 indexOf

_.indexOf(array, value, [isSorted])

6 lastIndexOf

_.lastIndexOf(array, value, [fromIndex])

7 sortedIndex

_.sortedIndex(array, value, [iteratee], [context])

8 findIndex

_.findIndex(array, predicate, [context])

9 findLastIndex

_.findLastIndex(array, predicate, [context])

Underscore.JS - Processing Array

Underscore.JS has many easy to use methods which helps in processing Arrays. This chapter discusses them in detail.

Underscore.JS provides various methods to process the Arrays as listed below −

Sr.No. Method & Syntax
1 flatten

_.flatten(array, [shallow])

2 without

_.without(array, *values)

3 union

_.union(*arrays)

4 intersection

_.intersection(*arrays)

5 difference

_.difference(array, *others)

6 uniq

_.uniq(array, [isSorted], [iteratee])

7 zip

_.zip(*arrays)

8 unzip

_.unzip(array)

9 object

_.object(list, [values])

10 chunk

_.chunk(array, length)

11 range

_.range([start], stop, [step])

Underscore.JS - Functions

Underscore.JS has many easy to use methods which helps in handling functions. This chapter discusses them in detail.

Underscore.JS provides various methods to handle functions as listed below −

Sr.No. Method & Syntax
1 bind

_.bind(function, object, *arguments)

2 partial

_.partial(function, *arguments)

3 memoize

_.memoize(function, [hashFunction])

4 delay

_.delay(function, wait, *arguments)

5 once

_.once(function)

6 before

_.before(count, function)

7 wrap

_.wrap(function, wrapper)

8 negate

_.negate(predicate)

9 compose

_.compose(*functions)

Underscore.JS - Mapping Objects

Underscore.JS has many easy to use methods which helps in mapping objects. This chapter discusses them in detail.

Underscore.JS provides various methods to handle object mapping as listed below −

Sr.No. Method & Syntax
1 keys

_.keys(object)

2 allKeys

_.allKeys(object)

3 values

_.values(object)

4 mapObject

_.mapObject(object, iteratee, [context])

5 pairs

_.pairs(object)

6 invert

_.invert(object)

7 create

_.create(prototype, props)

8 functions

_.functions(object)

9 findKey

_.findKey(object, predicate, [context])

Underscore.JS - Updating Objects

Underscore.JS has many easy to use methods which helps in updating objects. This chapter discusses them in detail.

Underscore.JS provides various methods to handle object updates as listed below −

Sr.No. Method & Syntax
1 extend

_.extend(destination, *sources)

2 pick

_.pick(object, *keys)

3 omit

_.omit(object, *keys)

4 defaults

_.defaults(object, *defaults)

5 clone

_.clone(object)

6 tap

_.tap(object, interceptor)

7 has

_.has(object, key)

8 property

_.property(path)

9 propertyOf

_.propertyOf(object)

Underscore.JS - Comparing Objects

Underscore.JS has many easy to use methods which helps in comparing objects. This chapter discusses them in detail.

Underscore.JS provides various methods to handle object comparison as listed below −

Sr.No. Method & Syntax
1 matcher

_.matcher(attrs)

2 isEqual

_.isEqual(object, other)

3 isMatch

_.isMatch(object, properties)

4 isEmpty

_.isEmpty(object)

5 isArray

_.isArray(object)

6 isObject

_.isObject(value)

7 isArguments

_.isArguments(object)

8 isFunction

_.isFunction(object)

9 isString

_.isString(object)

10 isNumber

_.isNumber(object)

11 isFinite

_.isFinite(object)

12 isBoolean

_.isBoolean(object)

13 isDate

_.isDate(object)

14 isRegExp

_.isRegExp(object)

15 isError

_.isError(object)

16 isSymbol

_.isSymbol(object)

17 isMap

_.isMap(object)

18 isWeakMap

_.isWeakMap(object)

19 isSet

_.isSet(object)

20 isWeakSet

_.isWeakSet(object)

21 isNaN

_.isNaN(object)

22 isNull

_.isNull(object)

23 isUndefined

_.isUndefined(value)

Underscore.JS - Utilities

Underscore.JS has many easy to use utility methods. This chapter discusses them in detail.

Underscore.JS provides various utility methods as listed below −

Sr.No. Method & Syntax
1 identity

_.identity(value)

2 constant

_.constant(value)

3 noop

_.noop()

4 times

_.times(n, iteratee, [context])

5 random

_.random(min, max)

6 mixin

_.mixin(object)

7 iteratee

_.iteratee(value, [context])

8 uniqueId

_.uniqueId([prefix])

9 escape

_.escape(string)

10 unescape

_.unescape(string)

11 result

_.result(object, property, [defaultValue])

12 now

_.now()

13 template

_.template(templateString, [settings])

Underscore.JS - Chaining

Underscore.JS has methods to create a chain of methods and then retrive their effective result. This chapter discusses them in detail.

Underscore.JS provides various utility methods as listed below −

Sr.No. Method & Syntax
1 chain

_.chain(object)

2 value

_.chain(obj).value()

Advertisements