Table of Contents
Key Takeaways
The Good Parts
_.each: Write Readable Loops
_.template(): Intuitive and Straightforward
_.filter(): All You Need Is a Boolean Function
Our Demo Application
Config Module
Template Module
Main Module
Conclusion
Frequently Asked Questions (FAQs) about Underscore.js
What is the main purpose of Underscore.js?
How do I get started with Underscore.js?
What are some of the most useful functions in Underscore.js?
Can I use Underscore.js with other JavaScript libraries?
Is Underscore.js still maintained and updated?
How does Underscore.js compare to other utility libraries like Lodash?
Can I use Underscore.js in a Node.js environment?
What is the ‘underscore’ in Underscore.js?
Can I contribute to the development of Underscore.js?
Where can I learn more about Underscore.js?
Home Web Front-end JS Tutorial Getting Started with Underscore.js

Getting Started with Underscore.js

Feb 18, 2025 pm 12:10 PM

Getting Started with Underscore.js

Getting Started with Underscore.js

Key Takeaways

  • Underscore.js is a JavaScript library that provides functional utilities for a variety of use cases, making code easier to read and write, and offering features not always available in native JavaScript.
  • The library includes common methods such as _.each() for writing readable loops, _.template() for intuitive and straightforward templating, and _.filter() for filtering arrays using a Boolean function.
  • Underscore.js is lightweight and used by many big name projects, including USA Today, LinkedIn, and Khan Academy.
  • A demo application using Underscore.js, jQuery, and the Spotify Web API demonstrates how the library can be used to fetch and display data from an API, and allows users to filter results.

This article was peer reviewed by Agbonghama Collins and Ryan Chenkie. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Underscore.js is a JavaScript library, written by Jeremy Ashkenas, that provides functional utilities for a variety of use cases that we, as developers, may come across when facing a web project.

It makes for code which is easier to read:

_.isEmpty({});
// true
Copy after login
Copy after login
Copy after login
Copy after login

It makes for code which is easier to write:

_.flatten([[0, 1], [2, 3], [4, 5]]);
// [0, 1, 2, 3, 4, 5]
Copy after login
Copy after login
Copy after login

It offers features for which there isn’t a 1:1 native method:

_.range(5);
// [0, 1, 2, 3, 4]
Copy after login
Copy after login

It can even be used as a template engine in its own right:

_.template('<p><%= text %></p>', {text: 'SitePoint Rocks!'});
// <p>SitePoint Rocks!</p>
Copy after login

Underscore is a lightweight library (just 5.7kb, minified and Gzipped) and is used by a variety of big name projects, such as:

  • USA Today
  • LinkedIn
  • Khan Academy

Now let’s get more specific and start diving into its main capabilities.

The Good Parts

In this tutorial, I’m going to highlight three of Underscore’s most common methods:

  • _.each()
  • _.template()
  • _.filter()

I’ll explain how they are used individually, then tie them together to build a demo application that you can find at the end of the tutorial. As ever, the code for this demo is available on Github.

If you wish to follow along with the examples, you’ll need to grab a copy of the library, for example from your favourite CDN:

<span><span><span><script</span> src<span>="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"</span>></span><span><span></script</span>></span>
</span>
Copy after login

And if you find yourself in need of help along the way, or you’re just curious to find out more, don’t forget that Underscore’s documentation is extensive. It also has a large and active community, meaning help is easy to find.

_.each: Write Readable Loops

There is not a single project that does not have something similar to this snippet at some point in the code:

var artists = ['Pharrel Williams', 'Led Zeppelin', 'Rolling Stones'];

for(var i = 0; i < artists.length; i++) {
  console.log('artist: ' + artists[i]);
}
Copy after login

Underscore enables you to write equivalent code, using a syntax that is more readable:

_.isEmpty({});
// true
Copy after login
Copy after login
Copy after login
Copy after login

Neat, eh? _.each() takes two parameters:

  • The array (or object) to iterate over.
  • A callback function.

For each element in our array _.each() will invoke the callback function (referred to in the documentation as iteratee). Inside the callback we get access to a further three parameters:

  • The value of the array for the current iteration index (artist). For example, for the snippet above we’d get “Pharrel Williams” for the first iteration.
  • The number of the current iteration (index), which in our case will vary from 0 to 2.
  • The array that we are iterating through (artists).

As you can see the code is more readable and we can access the individual elements in the array without the need for artists[i], as we saw in the example that used a for loop.

See the Pen _.each by SitePoint (@SitePoint) on CodePen.

Next, we’ll see how the templating engine behaves.

_.template(): Intuitive and Straightforward

Since the rise of the Single Page Application, having a reliable frontend templating engine has become a fundamental need for our working stack.

Underscore provides a templating engine, which, for those familiar with languages such as PHP, or Ruby on Rails, will seem quite familiar.

Carrying on from our previous snippet, we’ll demonstrate how _.template() works. We’ll do this by adding a couple of lines to our code as shown below:

_.flatten([[0, 1], [2, 3], [4, 5]]);
// [0, 1, 2, 3, 4, 5]
Copy after login
Copy after login
Copy after login

Here we are invoking the _.template() function with a string argument, which includes some data inside delimiters (). When invoked in this way, _.template() returns a function which we can use again and again.

We can invoke our new function using artistTemplate(), passing it an object literal as an argument. This will return the string we originally passed to _.template(), substituting any object properties which correspond to the template’s free variables. In our case will be substituted by the value in the artist attribute of the object.

Underscore’s templating engine, does not only allow for single values to be replaced, but also the execution of scripts inside the template itself. With a single modification, we can make our snippet even more powerful.

_.range(5);
// [0, 1, 2, 3, 4]
Copy after login
Copy after login

We have incorporated our call to _.each() into the string that represents our template, which leads us to change the way the template is invoked. Since we are now iterating inside the _.template() function, we can pass the complete artists array to artistTemplate() (previously we were passing the individual artists). The output of this code will be the same as in the previous example.

When we want _.template() to evaluate JavaScript code, we just have to surround our code between instead of .

Since invoking a template generated by _.template works just as invoking a function, we can take our snippet one step further and have one template called from inside another, by using the tags. This way, we can make reusable templates, since we can have a different wrapper template for our artists list and just invoke the template for each of the items it contains.

See the Pen _.template() by SitePoint (@SitePoint) on CodePen.

Finally, let’s take a look at the _.filter() function.

_.filter(): All You Need Is a Boolean Function

_.filter() receives an array and a callback function as arguments. It then invokes the function for each of the elements in the array and returns a new array containing those elements for which the function evaluated to something truthy.

Our callback function will also receive three arguments, as in the _.each() case: the element in the array corresponding to the current iteration index, the index of the iteration and the array itself.

To clarify this, let’s make a couple of modifications to our snippet.

_.isEmpty({});
// true
Copy after login
Copy after login
Copy after login
Copy after login

As you may have guessed, in our template we’ll receive ['ACDC']as the array argument. Here’s a demo of what we’ve got so far.

See the Pen _.filter() by SitePoint (@SitePoint) on CodePen.

Enough said. Let’s get things working for something that makes a little more sense.

Our Demo Application

Don’t forget, the code for this demo is available on Github.

We’ll build a small application which consumes an API, displays the information obtained and allows the user to filter what is being shown. For this purpose we’ll be using:

  • Underscore.js
  • jQuery
  • The Spotify Web API

More specifically, the application will fetch some artist information from Spotify and by using Underscore _.template, _.each and _.filter, we’ll display it on the page and allow the user to narrow the results by genre.

To do this, we’ll divide our code into three different modules:

  • _isAwesome.Config: holds the information that we’ll use across the application.
  • _isAwesome.Template: takes care of the template compilation.
  • _isAwesome: this is the main module which is responsible for responding to user actions and updating the UI.

All of them follow the Module Pattern.

Config Module

The Config module contains the ids of the templates to be used, together with the URL of the API that we’ll query, plus the ids of the artists that we want to get from Spotify. This way, we can add more artists by just adding further elements to the array.

Template Module

This module is the one in charge of compiling the templates, by calling getTemplates() in the Config module.

Main Module

This module is responsible for sending the Ajax request to the URL we get from the Config module and rendering the content using the templates from the Template module.

Aside from that, this module also takes care of filtering the items based on the filter clicked by the user.

Both the filters and our templates are included as part of the HTML.

To implement the filtering, we will rely on HTML 5 data attributes and jQuery’s data interface. This is more a question of convenience, but should you wish to do this natively, browser support is very good.

This is the markup of the buttons we’ll use to do the filtering:

_.isEmpty({});
// true
Copy after login
Copy after login
Copy after login
Copy after login

This is an example of an object we’ll be passing to our filter function:

_.flatten([[0, 1], [2, 3], [4, 5]]);
// [0, 1, 2, 3, 4, 5]
Copy after login
Copy after login
Copy after login

We’ll have the HTML for our templates as part of our index.html, inside a <script> tag, which we prevent from being executed by setting its type to something different than the usual text/javascript. Just for the sake of consistency we’ll set it to underscore/template.</script>

We’ll have two templates. The first will contain the list of artists, whereas the second will contain the individual artists to be displayed. As we saw above, we’ll use what we call embedded templates. We’ll be invoking one template ('item-tpl') from within another one ('item-list').

Then, at the bottom of the file we’ll include our libraries and our three scripts. Also, just to make it more visually appealing, we’ll have some basic styles in the header.

And that’s it.

See the Pen Underscore Awesomeness by SitePoint (@SitePoint) on CodePen.

Conclusion

Underscore is a joy to work with and, as I have demonstrated, it allows you to write clean, readable and easy-to-maintain code.

There are a couple more things that we could have added to our application (e.g. having our filters dynamically generated by using _.pluck()), but I think we have enough as to get started.

How about you? Have you worked with Underscore? Would you be willing to give a try? Did you try an alternative (i.e. lodash) that provides similar capabilities? Let me know in the comments below.

Frequently Asked Questions (FAQs) about Underscore.js

What is the main purpose of Underscore.js?

Underscore.js is a JavaScript library that provides a set of utility functions useful for common programming tasks. It’s designed to be a supplement to the built-in functions in JavaScript, providing extra functionality and enhancing productivity. It offers over 100 functions, including those that deal with arrays, objects, functions, and more. These functions help to manipulate data and objects in a more efficient and straightforward way, making it a valuable tool for developers.

How do I get started with Underscore.js?

To get started with Underscore.js, you first need to include it in your project. You can do this by downloading the library from the official website and linking it in your HTML file, or by using a CDN. Once it’s included in your project, you can start using its functions by calling them with the underscore character (_) followed by the function name.

What are some of the most useful functions in Underscore.js?

Underscore.js offers a wide range of functions, but some of the most useful ones include:

    1. _.each: This function allows you to iterate over an array or object’s elements.

    1. _.map: This function creates a new array by transforming every element in an array or object using a function.

    1. _.filter: This function returns a new array with all elements that pass a truth test.

    1. _.find: This function returns the first element that passes a truth test.

    1. _.reduce: This function reduces an array or object to a single value by iteratively applying a function.

Can I use Underscore.js with other JavaScript libraries?

Yes, Underscore.js is designed to be compatible with other JavaScript libraries. It doesn’t extend any built-in JavaScript objects, so it won’t conflict with other libraries or scripts running on your page.

Is Underscore.js still maintained and updated?

Yes, Underscore.js is actively maintained and regularly updated. The library is open-source, meaning that developers from around the world contribute to its development and improvement.

How does Underscore.js compare to other utility libraries like Lodash?

Both Underscore.js and Lodash offer similar functionality, but there are some differences. Lodash is a superset of Underscore.js, meaning it includes all of Underscore.js’s functionality and more. However, Underscore.js is smaller and lighter, making it a good choice for projects where performance is a concern.

Can I use Underscore.js in a Node.js environment?

Yes, Underscore.js can be used in a Node.js environment. You can install it using npm, the Node.js package manager, by running the command ‘npm install underscore’.

What is the ‘underscore’ in Underscore.js?

The ‘underscore’ in Underscore.js refers to the character (_) that is used to call the library’s functions. It’s a convention in JavaScript to use the underscore character for utility libraries.

Can I contribute to the development of Underscore.js?

Yes, since Underscore.js is an open-source project, anyone can contribute to its development. You can submit bug reports, suggest new features, or even contribute code.

Where can I learn more about Underscore.js?

There are many resources available to learn more about Underscore.js. The official website provides comprehensive documentation, and there are numerous tutorials and articles available online. Additionally, there are several books and online courses that cover Underscore.js in depth.

The above is the detailed content of Getting Started with Underscore.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

jQuery Matrix Effects jQuery Matrix Effects Mar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

How to Upload and Download CSV Files With Angular How to Upload and Download CSV Files With Angular Mar 10, 2025 am 01:01 AM

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular

See all articles