Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Functional JavaScript with Underscore.js

DZone's Guide to

Functional JavaScript with Underscore.js

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

JavaScript is a very versatile language, as it can be used for procedural, object-oriented or even functional programming.

For example, you can easily define anonymous functions in JavaScript at any point of the execution:

var f = function() { ... };

These functions can be passed around as variables, satisfying one of the prerequisites for functional programming:

doSomething(f, ...);

Anonymous functions become closures by binding automatically to existing variables any time you cite them in the implementation:

var selector = '#someId';
var html = function(content) { $(selector).html(content); };

By extending the pattern, it's also very easy to define functions that return other functions:

var write = function(selector) {
    var html = function(content) { $(selector).html(content); };
};

to implement some specific version of currying.

Underscore.js

There are several issues of functional JavaScript that Underscore.js tries to solve as an external library.

A first problem is that many primitives featured by functional languages, such as map, filter and reduce, are not present in the ECMAScript specifications.

Moreover, while it is a good idea to provide them into a cohesive library, we do not want to invade the global namespace or even the basic objects like Array by modifying their prototypes to add handy functions like Array.map(). In case we target a functional approach, we don't even need to attach functions to prototypes as they can remain a separate namespace.

Underscore.js is self-contained, and has no external dependencies; it provides every native function as part of a global _ object (e.g. _.map()). It follows that the conflict with other libraries and the existing data structures that your code rely on is minimal, yet the overhead for calling these function is the few characters of writing _.

Examples

Here is a self-contained HTML page that makes use of Underscore.js to perform some simple calculation, with the goal of showing you the implementation of some popular functional primitive like map and reduce.

This page depends also on jQuery for easy displaying of results, but Underscore.js can be used alone or in conjunction with other frameworks. Note that in this page I load the JavaScript source files remotely in their development version, to simplify the example.

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script type="text/javascript">
    $(function() {
        var primeNumbers = [2, 3, 5, 7, 11];
        var listIn = function(selector) {
            return function(num){
                $(selector).append('<p>' + num + '</p>');
            };
        }
        _.each(primeNumbers, listIn('#primenumbers'));

        var square = function(num) { return num * num; };
        _.each(_.map(primeNumbers, square), listIn('#theirsquares'));

        var sum = function(a, b) { return a + b; };
        var listInSum = listIn('#sum');
        listInSum(_.reduce(primeNumbers, sum, 0));

        var even = function(num) { return num % 2 == 0; };
        _.each(_.filter(primeNumbers, even), listIn('#even'));

        var odd = function(num) { return !even(num); };
        listIn('#allodd')(_.all(primeNumbers, odd));
    });
</script>
</head>
<body>
    <div id="primenumbers">Prime numbers</div>
    <div id="theirsquares">Their squares</div>
    <div id="sum">Their sum</div>
    <div id="even">The even ones</div>
    <div id="allodd">Are all primes odd?</div>
</body>
</html>

each is a primitive calling a function for each element of a collection (most of these primitives work both on arrays and objects).

map and reduce, made popular by Google's algorithm, repsectively collect the result of each in a new collection and collapse the elements of a collection into a single value.

Another very famous functional operation is the self-describing filter, but there are really many primitives included in Underscore.js, like all, any, reject, and find. In the case of arrays, which are the equivalent of lists in JavaScript, there are also the classic first, rest, zip, and so on.

Yet...

There is much syntax noise in coding in a functional style in JavaScript: it's a language not sharing much with the LISP family. For example, there is no support for automatic currying, or lazy evaluation of data structures. JavaScripts does not rely on referential transparency like the real functional languages like Clojure.

A different problem is efficiency, as it is the case every time you include an external library for basic operations like array manipulation. To deal with this issue, Underscore.js delegates to native functions where they are available: in that case basic operations like each will be compiled in the browser itself. In any case, you're shielded from having to check if the browser current supports such the function you want.

Resources

To learn more about functional concepts and how they apply to JavaScript, see this classic article on IBM developerWorks.

Higher-Order JavaScript guides you through the implementation of functional primitives and includes extended code samples.

If you want to start using Underscore.js, read the annotated source code as the primary form of documentation (which is generated from this anyway). Sometimes it pays to peek into a primitive you don't know how to call to really see what's going on.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}