An Introduction to Functional Programming in JavaScript

For me, in many ways, 2011 has been the year of the rediscovery of JavaScript. I have been programming in JavaScript for many years (like most other programmers) but now I’ve come to appreciate JavaScript the language a little better.

2011 was also when I had to dig into Scala. Thus I was compelled to implement more solutions in a functional manner.

Like many programmers unfamiliar with Functional Programming or others familiar with Functional Programming but more comfortable with Object Oriented Programming, it was daunting at first.

But persist through and one starts to see the benefits of Functional Programming (or at least understand it enough and execute your projects).

If you’re looking for a quick start in Functional Programming, JavaScript is the perfect language for you. Here’s why:

  • Almost all programmers have tweaked and / or written JavaScript code at some point of time — hence there should be a certain familiarity
  • JavaScript comes as close to a standardized programming language we’ll get — it’s the only programming language available across all web browsers
  • JavaScript comes with a very familiar C like syntax and should be readable to most programmers
  • Functions have always been first class members in JavaScript, support for Functional Programming is very good and in many ways JavaScript has been ahead of its time
  • JavaScript doesn’t have Java like Class based Object Oriented Programming support so in many ways you’re forced to be Functional in JavaScript

These should be enough reasons, so without meandering any further in the introduction, I present Functional Programming with JavaScript:

Functions in JavaScript

Almost everyone reading would have seen function declarations in JavaScript. However JavaScript lets you explicitly express functions as objects.

In fact, all function declarations are automatically converted to function expressions and hoisted.

By hoisting, the converted function expression is automatically placed in the beginning and thus is available in lines before it has been declared.

JavaScript functions are also different in the sense that each function, regardless of how it is defined, has dynamic arguments and a dynamic context.

A JavaScript function can, of course, access its arguments by their variable names.

By dynamic arguments, I mean, in the function body, we are provided an arguments array which contain all the arguments sequentially in the order they were passed. This means any function can be called with any set of arguments, thus giving us a lot of flexibility.

By dynamic context, I am refering to the this object. Typically the this object defaults sensibly to the context of the function. However it is possible to explicitly call a function with a user defined this / context object.

Notice how functionName.apply() allows us to explicitly set the context and pass arguments.

I must point out that JavaScript presents us with functional scoping instead of block scoping (C, C++ etc.). This usually becomes more relevant when you need to implement Object Oriented patterns in JavaScript but more on that in a later blog post.

Another trick for you is the capability to define self-executing anonymous function. These can be creatively used to implement modular namespaces / packages. Here are some examples:

Higher Order Functions

We know functions in JavaScript are nothing but objects. Does this mean functions can be passed around as arguments to other functions? And can one function return another function?

The answer to both questions is “Yes”. And such functions which taking in other functions are arguments and / or return functions are typically called higher order functions.

In the example below, we will define a higher order function forEach. This function takes in two arguments: a list and an action. The first argument list is an array containing containing objects and the second argument action is a function that will be invoked for each item in list.

The simple example above shows how a named function logItem and an anonymous function are being passed as arguments to the higher order function forEach.

Map / Reduce Implementations

In the example above, we saw how the forEach algorithm was expressed as a function and reused multiple times as an when required. We avoided repeating loops and thus made the code more readable.

This is one of the prime reasons to write functional code. If done correctly, you’ll be able to abstract out complex algorithms, replace it with a nice function call and keep code condensed and readable.

To further stress this idea, we need a better example. For each was too simple an algorithm to abstract. Let’s try implementing higher order functions for Map and Reduce algorithms.

We start with the Map function. What is the map function? Our map function should allow the user to perform a particular action over each item of a list, and then return a result list containing results of actions performed on each list item.

Simple enough, show me the code!

Notice we reuse the forEach function from the previous example. Our map function takes in two arguments, the first one being the mappingFunction that is to be applied on every item of the second argument list.

The implementation for map is straightforward. We prepare an array result, iterate through the list, call the mappingFunction for each item in list, push the result in the result array return it when all done.

As an example, we are calling map function and passing the function doubleIt as the mapperFunction on each item of an anonymous list.

Time for the reduce function. What is the reduce algorithm? The reduce function will be given a combine function, a base value and a list. We need to apply the combine function on the base value and each value in the list and finally return the result. In short, Reduce function takes in a list, combines it and gives us a single result.

This solution again makes use of the previous create forEach function. Our reduce function is simple, it iterates through the list, applies combine on base and each list item, stores the result in base and returns it after completion.

As a usage example, we use reduce to get a count of the negative numbers in a list.

These two examples are fairly simple and still show us how, with functional programming, we can effectively abstract out algorithms as functions, use them as and when required and still retain simplicility and readability in the code.

Closures in JavaScript

If you’ve heard of Functional Programming, there’s a very good chance you’ve also heard about closures. They are often mentioned in the same breath.

But what are closures? Think of closures as a composite of two things:

  1. A function being returned by another function
  2. A closed environment in which this returned function is forced to execute

This is what a closure is.

In our first example of a closure implementation, we have getAreaFunction which reads the shape argument and returns an appropriate area function.

Notice how getAreaFunction returns an anonymous function. This returned function contains a switch case on shape which is available in the environment.

Finally, of course, we see how to use the closure as a function factory to get area functions for different types of shapes.

In our second closure example, we see how closures are used to implement private class members in JavaScript.

I’ll not explain Object Oriented Programming implementations in JavaScript as part of this post. They aren’t complex but are different, surely worthy of a dedicated post.

If you’re already familiar with OOP concepts and their implementations in JavaScript, note how the class Shape (which is, yes, expressed as a function) contains a private function area and isn’t exposed.

Instead an instance function getArea is available which does internally make use of the private function area.

This is one of the most common use-cases of closures in JavaScript.

Another classic use-case for closures in JavaScript is to avoid the annoying problem that crops up every time you try to set event handlers within a loop.

Consider the following example:

In the for loop, we first assign an onclick handler to all the red boxes. However, thanks to functional scoping, all three red boxes have onclick handlers with redBoxId value 3.

However for green boxes we assign onclick handlers in a slightly different manner. We have a self executing anonymous function which returns another function which then is assigned as the onclick handler.

Due to functional scopes, each onclick handler for the green boxes have correct values for greenBoxId.

I realize this has been a fairly lengthy post. Will end it now. Hopefully this would have served as a good enough introduction to Functional Programming concepts and their corresponding implementations in JavaScript.

All code available on GitHub.