Underscore.js – Everything you didn’t know you needed

Underscore.js (_.js for short) is a phenomenal javascript library that most web and Titanium developers are likely familiar with at this point.  What you may not know is that _.js is bundled with Alloy, letting you use the awesome collection of commonly used functions with little effort on your part.  I’ve compiled a few of my favorites here:

_.each

Underscore’s each function is a great alternate to Javascript’s built in for function, with the key difference that it allows you to have a local scope to work in (as opposed to Javascript’s built in for, which inherits the parent scope).


var people = [{name : "john"}, {name : "amy"}, {name : "bill"}];
//traditional for loop
for (var i = 0; i < people.length; i++){
  var person = people[i];
  Ti.API.info(person.name);
}
//this will print out 'bill' again, since the for uses the parent's scope
Ti.API.info(person.name);

//with _.each
_.each(people,function(person2){
  Ti.API.info(person2.name);
}
//but this won't work, since person2 is out of scope!
Ti.API.info(person2.name);

_.memoize

Memoize does exactly what the name says!  It takes a function, and returns a version of it that will only calculate its return value once for a given set of inputs, and then cache this value and return it on subsequent calls.  It’s absolutely great for functions that always give the same result but can take a long time to compute (the Fibonacci sequence is an oft-used example).  For more information, Wikipedia has a great page on memoization.

Another great use would be for hash functions (e.g. the also-bundled-with-alloy sha1)


var sha1 = require('alloy/sha1');
//memoize the hash function
var cachedSha = _.memoize(sha1.hex_sha1);
//now you can use the memoized version like any other js function!
var hash = cachedSha("hash me!");

_.isWhatever

Underscore provides a awesome set of isSomething functions that can tell you all kinds of things about a given variable, ranging from its type to whether it is finite. Examples include isEmpty, isArguments, and isDate.


_.isEmpty({});//true
_.isArray([]);//true
var notArguments = [1,2,3];
_.isArguments(arguments);//true
_.isArguments(notArguments);//false
_.isString(NaN);//false
//etc. etc.

_.once, _.throttle, and other function modifiers

_.once and _.throttle are great for controlling frequency of execution of functions. Simply put, _.once makes it so a function can only be executed once, and _.throttle rate limits a function so that it can only be executed once every so often (e.g. at most once every 200 ms).  Both are extraordinarily useful in the context of Titanium for dealing with issues associated with events getting created too quickly to be handled in a sensical fashion, such as a user tapping a button too quickly or scrolling too fast. Other awesome function processing functions include _.after (provided function is executed after being called a certain number of times), and _.debounce (function is only executed after it hasn’t been called for some period of time).


//only initialize the app once
var init = _.once(function(){
  //stuff here
});
init();
init();
//was only executed once

And more!

Underscore.js contains roughly 80 different commonly used functions for different purposes, too many for me to possibly go over here.  Take a look at their docs, and feel free to leave comments about your favorites below!

Alex Otañez

Alex Otañez

December 20, 2013

Alex has more than 10 years of international experience in Strategic IT Transformation and Custom App Development. His expertise in various industries ranges from Consumer Goods to Retail to Finance while assisting clients in the areas of Business Strategy & Development, Security & Compliance, and Technology Transformation. As one of Shockoe’s founding members, Alex is focused on business strategy, security & compliance, digital innovation, mobile management, and operational transformations.

More like this delivered right to you:

Sign up for our Newsletter to get our latest posts plus invitations to our events and access to future whitepapers.

Related Posts

7 Tips for Utilizing Amazon Alexa to Engage with Customers

7 Tips for Utilizing Amazon Alexa to Engage with Customers

Amazon first released Alexa virtual assistant and smart speaker Echo in late 2014. An in-home virtual assistant is an impressive tool, but creating a seamless user experience with it can be a challenge. So how do companies overcome this challenge? What engagement can...

How to Engage Customers With QR Codes and Augmented Reality

How to Engage Customers With QR Codes and Augmented Reality

When one of our clients approached us with the idea of building an entirely new customer engagement app for their grocery stores, we were very excited. Their goal was to build a mobile application that customers could use to learn about products, find them in the...

Ready to drop us a line?