BAM Weblog

JavaScript as a Functional Language

Brian McKenna2010-04-28

This post has been modified from an answer I posted on Stack Overflow.

A lot of people misunderstand JavaScript, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml behave and look completely different).

JavaScript is sometimes called object-oriented. It is a loosely-typed dynamic language and doesn't have classes nor classical inheritance. This means that when JavaScript is compared to Java or C++, the concepts just don't match up.

I find that JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as partial application (currying).

Today's aim is to make a piece of JavaScript act more functional. Let's take an example (using sys.puts from node.js):

var external;
function foo() {
    external = Math.random() * 1000;
}
foo();

sys.puts(external);

To get rid of global side effects, we can wrap it in a closure:

(function() {
    var external;
    function foo() {
        external = Math.random() * 1000;
    }
    foo();

    sys.puts(external);
})();

Notice that we can't actually do anything with external or foo outside of the scope. They're completely wrapped up in their own closure, untouchable.

Now, to get rid of the external side-effect:

(function() {
    function foo() {
        return Math.random() * 1000;
    }

    sys.puts(foo());
})();

That's as far as we'll get. In the end, the example is not purely-functional because it can't be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.

I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:

var Square = function(x, y, w, h) {
   this.x = x;
   this.y = y;
   this.w = w;
   this.h = h;
};

function getArea(square) {
    return square.w * square.h;
}

function sum(values) {
    var total = 0;

    values.forEach(function(value) {
        total += value;
    });

    return total;
}

sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
    return getArea(square);
})));

Some Lisps even have things called property lists which can be thought of as objects.

The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a new object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).

I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for you.

Please enable JavaScript to view the comments powered by Disqus.