Computer Science, JavaScript, Musings

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:

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

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

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

Closures

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.

Lastly…

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.

About these ads
Standard

26 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. :)

      • 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. Pingback: How to Add a Character Counter to the WordPress Post Excerpt Box « 12oy.wordpress.com

  3. Ian says:

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

  4. vxl23 says:

    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).

  5. Pingback: Clean Code, Dirty Code « CodeKraft

  6. Pingback: Events in JavaScript « CodeKraft

  7. Pingback: Static and Instance Methods in JavaScript | CodeKraft

  8. Pingback: A peek into JavaScript’s Array.prototype.map and jQuery.map | CodeKraft

  9. Pingback: The JavaScript Function | CodeKraft

  10. Pingback: Three Important JavaScript Concepts | CodeKraft

  11. Pingback: Defining JavaScript Functions | CodeKraft

  12. Pingback: The Immediately Invoked Function Expression | CodeKraft

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s