Home

Underscore: A Utility Belt for JavaScript

|
Updated:  
2016-03-26 07:58:52
|
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

Underscore is a collection of more than 100 useful JavaScript functions to help you get started and be more productive with JavaScript. To use Underscore’s functions on a web page, you need to include it using the script element. You can either include the library within the head element or load it right before the closing body tag in order to avoid blocking the loading of your web page while Underscore is loading.

Like any JavaScript library, you can either download Underscore and link to it on your own server or link to a hosted version. You can find a link to the latest version at http://cdnjs.com/libraries/underscore.js/.

To use Underscore’s functions after you’ve included the library, just preface the functions with an underscore and a period. For example, Underscore’s random function returns a random number between two numbers passed as arguments. The following statement will return a random number between 0 and 999:

_.random(0,999)

Check out a complete list of functions provided by Underscore on the library’s website. Here are a few of the many useful functions.

FunctionWhat It Does
find Looks through the values in a list and returns the first one that passes a test.
filter Looks through the values in a list and returns an array of all the elements that pass a test.
sortBy Returns a sorted copy of a list.
countBy Sorts a list into groups and returns a count of the items in each group.
Pluck Extracts an array of values from an object or array.
max Extracts the largest value in a list.
min Extracts the smallest value in a list.
shuffle Returns a shuffled version of a list.
sample Returns a random sample of items from a list.

Once you get to know the functions in Underscore and start to use them, you’ll quickly understand why some people feel it’s the single most useful JavaScript library ever.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.