Features of Underscore.js


Underscore.js is a lightweight library and compatible with all major browsers, as well as Node.js. It can be useful when working on projects involving a lot of data manipulation, as it provides several powerful tools for working with arrays and objects in JavaScript.

Underscore.JS is a popular utility library; many other JavaScript libraries and frameworks like Backbone.js, AngularJS, and React.js use it as a dependency.

Before we talk about its features, you can go to the official website of Underscore.js (http://underscorejs.org/) and download the minified version (underscore-min.js) of the library. We will set the path of this version in the ‘src’ attribute of <script> tag.

Syntax

Below is the syntax for doing the same.

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

We will use it in the below examples.

Let us understand various features of underscore.js using different examples.

  • Iterating Collections

  • Processing Collections

  • Arrays

  • Objects

  • Utilities

  • Chaining

Iterating Collections

Underscore.js has many methods like map, each, find, filter, reduce, reduceRight, reject, every, some, where and findWhere, which helps in iterating Collections.

Example

In the below example, we will understand the use of the _.where() method.

<html>
<head>
<script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Iterating Collections </h2>
   <div id = "output">
   </div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      var people = [
         {name: "Om", age: 23},
         {name: "Shuman", age: 23},
         {name: "Vivek", age: 24}
      ];
      output.innerHTML = _.where(people, {age: 23});
   </script>
</body>
</html>

Users can observe in the above code that we have made a list of 3 people with name and age. Inside the _.where() method, we are passing that list, and age: 23 as an argument to search people having age 23. We have two people with age 23. So, we get two objects in the output.

Processing Collections

Underscore.js provides methods like - invoke, contains, max, min, pluck, shuffle, sample, toArray, size, partition, and compact, which helps processing Collections.

Example

In the below example, we will understand the _.shuffle() method.

<html>
<head>
   <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Processing Collections </h2>
   <div id = "output">
   </div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      output.innerHTML = _.shuffle([1, 2, 3, 4, 5, 6, 7]);
   </script>
</body>
</html>

Users can observe in the above code that we have shuffled a list containing numbers from 1 to 7 using the _.shuffle() method.

Arrays

Underscore.js provides methods like – first, initial, last, rest, indexOf, lastIndexOf, sortedIndex, findIndex, and findLastIndex, which helps in iterating Arrays. And also it has methods like – union, intersection, difference, uniq, flatten, without, zip, unzip, object, range, chunk, which helps in processing Arrays.

Example

In the below example, we will understand the _.without() method.

<html>
<head>
   <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Arrays </h2>
   <div id="output">
   </div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      output.innerHTML = _.without([1, 2, 3, 4, 5], 2, 5);
   </script>
</body>
</html>

In the above example, it can be noticed that using the _.without() method, we have excluded 2 and 5 from the list of numbers.

Functions

Underscore.js provides methods like memoize, partial, bind, delay, before, once, negate, compose, and wrap, which helps handle functions.

Example

In the below example, we will understand the _.bind() method.

<html>
<head>
   <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Functions </h2>
   <div id="output"> </div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      let obj = {
         id: 1,
         name: "John"
      };
      let ref = _.bind(
      function print_message(){
         output.innerHTML = "Hey " +this.name+ "! How are you?";
      }
      , obj);
      ref();
   </script>
</body>
</html>

Users can observe in the above code that using _.bind() method, we have replaced the occurrence of this in a function with a reference of the passed object.

Objects

Underscore.js provides methods like – keys, allKeys, findKey, values, pairs, invert, mapObject, functions, create, which helps in mapping objects. It has methods like – pick, omit, extends, defaults, tap, has, clone, property, propertyOf, which helps in updating objects. And it also provides methods like – matcher, isEqual, isEmpty, isArray, isString, isNumber, isRegExp, isMap, isUndefined, isError, etc., which help in comparing objects.

Example

In the below example, we will understand _.keys(), _.pick(), _.isString() and _.isObject() methods.

<html>
<head>
   <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Objects </h2>
   <div id="output"> </div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      let obj = {
         name: "Peter",
         rollNo: 5
      };
      output.innerHTML = "keys: " + _.keys(obj) + "<br>";
      output.innerHTML += "pick: " + _.pick(obj, "name").name + "<br>";
      output.innerHTML += "is String: " + _.isString(obj) + "<br>";
      output.innerHTML += "is Object: " + _.isObject(obj);
   </script>
</body>
</html>

The example which is given above shows the use of different methods to handle objects related operations.

Utilities

Underscore.js has different utility methods such as constant, noop, identity, random, mixin, times, iterate, uniqueId, escape, unescape, template, now, and result.

Example

In the below example, we will understand the _.random() method.

<html>
<head>
   <script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Utilities </h2>
   <div id="output"></div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      
      //Get a random number between 5 and 20
      output.innerHTML = _.random(5, 20) + "<br>";
      output.innerHTML += _.random(5, 20) + "<br>";
      
      //Get a random number between 0 and 10
      output.innerHTML += _.random(10) + "<br>";
   </script>
</body>
</html>

In the example given, it can be observed that we are getting random numbers in a range which is given as arguments.

Chaining

Underscore.JS has methods like _.chain(object) and _.chain(object).value().

Example

In the below example, we will understand _.chain(object).value() method.

<html>
<head>
<script type = "text/JavaScript" src = "https://underscorejs.org/underscore-min.js"></script>
</head>
<body>
   <h2> Chaining </h2>
   <div id="output"></div>
   <script type = "text/JavaScript">
      let output = document.getElementById("output");
      output.innerHTML = "maximum value: " + _.chain([1, 4, 2, 8, 3, 6]).max().value();
   </script>
</body>
</html>

In the example given above, the max value object is wrapped, which is returned by the value() method.

We have learned how to add underscore in the code and various features of Underscore.JS.

Updated on: 17-Mar-2023

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements