JavaScript: The functional Programming Parts

Yes, a lot of people think JavaScript is just another object-oriented language but the language differs in many ways from the Java/C++ class of programming languages. For example, JavaScript uses prototypical inheritance versus the classical inheritance favoured by OO languages; this makes it easier to get on new behaviours… and also makes it really really easy to shoot yourself in the foot.

All languages have their strengths and flaws and JavaScript is not left out – a lot of people even think it is a bad bad language full of flaws and mistakes. However I believe the language is quite beautiful and Brenden Eich certainly got some things right in its design. Douglas Crockford (know him? He’s a JavaScript advocate and invented JSON + JSLint) said JavaScript is like “Lisp in C’s clothing”; possibly due to JavaScript’s Self and Scheme roots. Scheme, one of the dialects of Lisp, is a weird cool language that uses the prefix notation (pretty strange to me coming from an infix background) and has some interesting features like first-class continuations and lambda calculus

Here are some of the functional aspects of JavaScript:

First-class functions

One of the core features of functional programming is supporting functions as normal data, most other languages differentiate between data and programs. Functional programming allows you to use and treat functions as you’ll treat data. As such, you can store functions in variables, create functions on the fly during execution of programs (just as you’ll create variables normally in other languages), return functions from functions, pass functions as arguments to other functions. Cool stuff right? And some sample code:

// creating and returning functions on the fly
function Counter() {
     var i  = 1;
     return function () {++i;} 

// assigning variables to functions 
var func = function () { ... } 

// passing functions as arguments
function doSomething (function callback) {


Now I love this one. Closures are a way of hiding your data and making them ‘private’. It is awesome and cool to use. Closures are functions that can refer to variables outside of the context they were created in.

var makeCounter = function () {
     var count, f;
     count = 0;
     f = function () {
         count = count + 1;
         return count;
     return f;
var counter = makeCounter();
/* counter is a function that takes no arguments and returns a count */ 

var a = counter(); 
// => 1 

var b = counter(); 
// => 2 

var c = counter(); 
// => 3

Closures are used to do event binding, callbacks, sorting, mapping and other stuff. An example is the jQuery sample code below:

(function() {
    var jQuery=window.jQuery=window.$=function(selector,context) {           
    // ...

The jQuery code is executed as an anonymous function immediately, however the variable function names, jQuery and $ are exposed and can be used outside the anonymous function. The body of the entire jQuery code is protected from manipulation by outside code, this ensures that its variables are kept hidden and enables exposing those methods that we all know and love.


There are other properties of JavaScript too such as currying, lambdas (anonymous functions), higher-order function support although it lacks some other features of functional programming languages such as tail-call optimization, it’s is variable-oriented language and has side-effects too.

Also jQuery exploits a lot of the Lisp roots of the JavaScript language; these include list processing (remember that selectors return lists) and method chaining ( I think this is just a cover for the continuation passing style).

Should you learn about functional programming? I think so; it’ll improve the way you think about programming, well I admit you might never have to use it but it should make you better.

Related articles

33 thoughts on “JavaScript: The functional Programming Parts

  1. Nice one! Anonymous functions and Closures are pretty similar except Closures are usually used inside your own function and the data hiding feature(most of the code I see/write). Higher-order functions; that I haven’t used and most times, you pass in an Anonymous function as an argument. I’m really looking forward to working on a hardcore JS project. With the rise of NodeJS and more awareness about the strenghts of JS, Methinks JS is coming into it’s own. A long overdue glory. :)


      1. Wa iyakum. It has found a nice place in HTML5. I really wish I can use it more. All we seem to be doing with it is just spicing up pages, client-side validation etcetera! I want to do more than that with it; maybe work with it server side. Barakallah feeh!


  2. There is a typo in your closure example. The function you define is Counter, but when you call it you call it makeCounter.


  3. While closures are nice, you still should take extra care when using them: If you use them in loops, the garbage collector might not be able to collect them, effectively creating a memory leak (making your browser eat memory over time).


      1. Basically – a closure creates a new gc root context, where you can declare variables that will not be GC’d, otherwise your counter would return ‘undefined’ after some time.

        Last year I wrote a visualization webapp that died after some time exactly because of that. One part have been closure leaks in the graph library we used, we ourselves introduced some by using ajax calls to get new data via timers (we attached variables to the XMLHttpRequest object, which would call a function to create a new request object after some time, … and so on ).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.