Underscore.js | Top 10 Useful Functions with Examples

Prayukti Jain
Nerd For Tech
Published in
9 min readJun 14, 2021

--

Underscore.js | Understand one of the most useful libraries of JavaScript
Underscore.js | Understand the most useful library by JavaScript

Javascript supports several libraries just to make the tasks easier and fast. Underscore.js is one such javascript library that provides a cluster of useful javascript functions that can make developers' lives easier. The underscore.js library includes our workaday functions as well as the exclusive functions, about which we will learn about in the coming sections. So let’s get started with the feature set provided by the underscore.js library.

Underscore.js - Features

Underscore.js is a lightweight and superficial JavaScript library, that is not a complete framework but facilitates utility functions for a variety of cases in our common programming chore. Underscore.js comprises of utilities that can be broadly categorized as:

  1. Handling the alterations on the arrays.
  2. Handling the alterations on the objects.
  3. Handling the alterations on the functions.

Underscore.js also supports the chaining utilities as well, for better performance. And, hence using Underscore.js, developers can fetch, manipulate, sort, and filter data according to the usage.

Underscore.js - Setup

Now, before moving on to the working part of the Underscore.js, we require to access the Underscore.js library. You can either use it in the browser by including the respective script from the official website or by installing it on your machine. Both of the ways have been briefed below.

Using Script for Underscore.js in the Browser

For this, you need to visit the official Underscore.js website and get to the downloads section, wherein you can get the dependencies available and you can save them according to your consumption.

Post this, you can just add this script tag to your HTML header and get started on using Underscore.js.

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

Using the installer to get the dependencies for Underscore.js

Another way of using it is, to install the Underscore.js dependencies via the NPM installer. For this way of accessing the library, make sure you have node.js and npm installed on your machine already. You can use the following command to install Underscore.js via node.js itself.

npm install underscore

After the successful execution of this command, you can just include it in your node.js script using the following command and start working with the Underscore.js library.

var _ = require('underscore');

Note: _ is used as a variable name because of the library name, but you can use any other suitable name while working on your own. _ is just widely used to work with the library, hence the examples would also include the same.

Underscore.js - Useful functions with examples

We have already included the library on the systems, now we will see how we can get the most of it by working with the Underscore.js library. This section includes the most useful functions, with their uses, syntax, and examples for better understanding. So, let’s get started!

Note: Assume the respected script and library dependencies have already been included and therefore, are not specified in the snippets.

_.each()

This is the Undescore.js library function that allows you to iterate over your collection and on each iteration, you are free to do whatever you want to do with the value. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
_.each(numbers, function(value, index){
console.log(value, index);
});

According to the snippet, each function takes 2 things, the collection and the function that needs to be executed on each iteration and for each value. This function gets 2 things on each iteration, the value for the iteration and the index of the value in the collection. You can implement this function in any possible and suitable manner based on the usage.

For this sample snippet, the following would be the output:

Underscore.js | each function

The each function of the Underscore.js library can work on any javascript object similarly. For example, if you have the following data, you can use this function to iterate over all the attributes present in the data. On each iteration, you will be having access to the key/index and the value from the collection.

var data = {name: “Tom”, age: 18, gender: “male”};
_.each(data, function(value, key){
console.log(key, value);
});

_.map()

This is the Undescore.js library function that allows you to iterate over your collection or any javascript object and on each iteration, allows you to manipulate the values. Following is the way you can use this function.

var numbers = [10, 20, 30, 40, 50];
var halfNumbers = _.map(numbers, function(value, index, items){
return value / 2;
});
console.log(halfNumbers);

According to the snippet, you will have a new collection that would have half of the value of the original one. Also, the map function takes 2 things, the collection/object, and a function. This function makes the value of the iteration, the index of the value in the collection, and the original collection available on each iteration. Following would be the output of the above snippet.

Underscore.js | map function

You can also alter the original array instead of taking a new one. For doing this, your code snippet would look like this:

var numbers = [10, 20, 30, 40, 50];
_.map(numbers, function(value, index, items){
items[index] = items[index] / 2;
});
console.log(numbers);

_.reduce() and _.reduceRight()

This is the Undescore.js library function that allows you to iterate over your collection and reduce them into a single value. For example, it can be used to get the sum of all the elements in the array. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
var sum = _.reduce(numbers, function(total, value, index, items){
return total + value;
});
console.log(sum);

According to the snippet, reduce function takes the collection and a function. This function makes the running total or total so far, the value for the iteration, the index of the value, and the original collection available on each iteration. Following would be the output of the above snippet.

Underscore.js | reduce function

There is another similar function, the reduceRight function, that also works for the same utility with the same syntax. The only difference between the reduce and reduceRight function is that, the reduce function starts the iteration from the start of the collection while the reduceRight function starts the iteration from the end of the collection. You can similarly use the reduceRight function as reduce function and can change implementation according to the usage.

_.find() and _.filter()

This is the Undescore.js library function that allows you to iterate over your collection and finding the value in that collection based on the algorithm implemented. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
var found = _.find(numbers, function(number){
return number % 2 == 0;
});
console.log(found);

This find implementation is expected to find the first even number from the collection and return it, that is 2 in this case. If you want to get all the even numbers from the collection and not just a single one, you can similarly use the filter function. Using the filter function, the output would look like the following.

Underscore.js | filter function

_.where() and _.findWhere()

This is the Undescore.js library function that allows you to iterate over your collection and enable you to find the value based on the where clause. Following is the way you can use this function.

var data = [
{name: "A", age: 23},
{name: "B", age: 23},
{name: "C", age: 21}
];
var found = _.where(data, {age: 23});
console.log(found);

This where implementation would return the list of objects that are matching the clause provided to the where function. Hence the output would look like the following.

Underscore.js | where function

Now, if you want to get only the first instance of the object that matches the where clause, you can use the findWhere function that works similarly and just return the first instance rather than all the matching instances.

_.some()

This is the Undescore.js library function that allows you to iterate over your collection and checks that at least one of the values matches the algorithm that you have defined. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
var found = _.some(numbers, function(number){
return number > 4;
});
console.log(found);

Now, according to the implementation, some function will return true if it gets a number greater than 2 or else will return false. Hence, the following would be the output of the above snippet.

Underscore.js | some function

_.invoke()

This is the Undescore.js library function that allows you to iterate over your collection and executes a function on each element of that collection. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
function generator(factor){
return this * factor;
};
var factor = 3;
var result = _.invoke(numbers, generator, factor);
console.log(result);

According to the snippet, the invoke function will be executed and on each iteration, the generator function will be executed for the respective value and the factor would be passed to the generator function. The generator function multiplies the number with the factor and returns it. Hence, the output of the above snippet would look like this when the factor is 2 and 3 respectively.

Underscore.js | invoke function

_.sample()

This is the Undescore.js library function that allows you to iterate over your collection and returns a sample from that list based on the parameter. You can change the number of values you need as the sample from the complete collection. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5];
var sampleCount = 4;
var sample = _.sample(numbers, sampleCount);
console.log(sample);

According to the snippet, the sample function will just return a random sample from the list of numbers given. And the random output would be of the size as sampleCount. Hence, each time you execute the script, you will get different output as shown below.

Underscore.js | sample function

_.uniq()

This is the Undescore.js library function that allows you to iterate over your collection and removes the duplicates from the array. Following is the way you can use this function.

var numbers = [1, 2, 3, 4, 5, 1, 2];
var unique = _.uniq(numbers);
console.log(unique);

The output of the above snippet would not include the duplicate values present in the collection. This can be used in other ways as well like, if the data of several people is given and you need to find out unique people based on their age, you can use the following snippet.

var data = [
{name: 'A', age: 21},
{name: 'B', age: 21},
{name: 'C', age: 22},
{name: 'D', age: 23}
];
var unique = _.uniq(data, false, function(person){
return person.age;
});
console.log(unique);

The uniq function takes the collection, a flag variable to indicate the unordered array, and a predicate function, that returns the parameter which determines whether the person is unique or not. Also, it will always keep the first non-unique value as part of the result. Hence, the output of the above snippet would look like this.

Underscore.js | uniq function

_.flatten()

This is the Undescore.js library function that allows you to iterate over your collection that consists of nested collection and flattens it all into a single level. Following is the way you can use this function.

var numbers = [1, 2, [3], [4, [5]]];
console.log(_.flatten(numbers));

This snippet would convert the number array and flatten it to a single level and output would be just [1, 2, 3, 4, 5]. Another argument can be passed to specify whether it needs to be flattened to just a single level. That is if flatten is called and a true is passed after the numbers array, then it will lead up to the following output.

Underscore.js | flatten function

Conclusion

In this article, we came across various useful functions and their implementations in the underscore.js framework. Using this would be beneficial as it would optimize your run time and make the code precise and readable. I hope you found this helpful and knowledgeable.

Do look out for other articles to get the knowledge about various topics and feel free to drop a comment for doubts or suggestions.

What are the top 10 useful functions of Underscore.js?

What are Decorators in Python?

Multithreading in Java

Understanding Apache Derby using Java

TCP/IP Socket Programming in Java

How to send HTTP Requests using React JSX?

--

--

Prayukti Jain
Nerd For Tech

Software Engineer at Microsoft | ex - Walmart | Content Writer | Open to Learn and Help