JavaScript and Russian Dolls

In JavaScript, functions are variables which means they can be created and replaced at run time. Thanks to the pioneering efforts of Richard Cornford (Russian Doll Pattern, 2004), Peter Michaux (Lazy Function Definition pattern, 2007) Oliver Steele (One-Line Memoization, 2006) there are nifty techniques that exploit this capability.

First, a very simple example to illustrate the principle:-

var pushTheRedButton = function() {
    //reassign a new function to the variable pushTheRedButton
    pushTheRedButton = function() {
        //this line gets called on all subsequent visits</span>
        alert("Now look what you've done!");
    }
    //this line only gets called on the first visit</span>
    alert("Don't ever push this button again!");
}

pushTheRedButton(); //"Don't ever push this button again!"
pushTheRedButton(); //"Now look what you've done!"

Continue reading “JavaScript and Russian Dolls”

The module pattern (in a nutshell)

The module pattern (first publicized by the Yahoo! JavaScript team) makes use of closures to bake privacy and state into your objects.

This is the generic form…

function() {
    //private state
    //private functions
    return {
         //public state
         //public variables
    }
}

Continue reading “The module pattern (in a nutshell)”

How evil is eval?

“eval is Evil: The eval function is the most misused feature of JavaScript. Avoid it”

Douglas Crockford in JavaScript: The Good Parts

I like The Good Parts. It’s essential reading for anyone who’s serious about JavaScript – and I realize that Crockford’s goal here is to emphasize only what he likes – but still I think that such a brief yet total rejection might send the wrong message.

Continue reading “How evil is eval?”

Compose: functions as building blocks

As regular readers have probably noticed, a recurring theme of these posts is function manipulation as an expressive device. JavaScript treats functions as first class objects, that is they can be created and modified dynamically and passed as data to other functions and objects. Shamelessly continuing this theme, allow me to introduce functional composition…

Here’s a couple of simple examples to start:-

var  alertPower = alert.compose(Math.pow);
alertPower(9,8); //alert shows 43046721
var  roundedSqRoot = Math.round.compose(Math.sqrt);
roundedSqRoot(28); //5

Continue reading “Compose: functions as building blocks”

Curry: cooking up tastier functions

Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:

var add = function(a,b) {
    return a + b;
}

var addTen = add.curry(10); //create function that returns 10 + argument
addTen(20); //30

Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.

Continue reading “Curry: cooking up tastier functions”

Five ways to create objects – part 2: Inheritance

Let me start by saying I think inheritance is somewhat overrated in JavaScript. A lot of the inheritance you are going to need is already created for you: Function, String, Number etc. all inherit Object via its prototype.

I actually wonder if more energy goes into intellectual exercises around JavaScript inheritance than into using inheritance for real time solutions. Yes, JavaScript has an excellent inheritance mechanism but lets face it all those examples with furry animals, hierarchies of wheeled vehicles and the like have little real world application in client side coding.

How often do your new objects really need to inherit from other new objects you have created? By its nature the client object modelling is essentially flat (like your monitor). If you find yourself in JavaScript creating complex java-style object models with layers of inheritance then you might want to ask yourself why. Ajax allowed us to defer to the server where we used to have to clone our business/server logic on the client. I’d argue such complex data structures are best left to the server, because they perform better, are more easily distributed across subsystems and are probably more suited to classical OOP.

With that said, JavaScript does offer a very nifty inheritance strategy – there are no classes – objects inherit from objects. Period. It’s clean and its simple.

So here goes..

Continue reading “Five ways to create objects – part 2: Inheritance”

The Case against Switch

I’ve never been fond of switch statements, whether in JavaScript or Java. They’re big and hard to follow, and of course if you forget the break keyword after each case you enter fall-through hell. (Since break statements are almost always intended it seems a pain to have to add them manually). Using objects as hash table for look-up is a simple and elegant alternative:

Example 1: Using switch is hard to read and the data is mixed with the logic

var whatToBring;
switch(weather) {
    case "Sunny":
        whatToBring = "Sunscreen and hat";
        break;
    case "Rain":
        whatToBring  ="Umbrella and boots"
        break;
    case "Cold":
        whatToBring = "Scarf and Gloves";
        break;
    default : whatToBring = "Play it by ear";
}

Example 2: Pull data into object construct. Data and logic are separated.

var whatToBring = {
    "Sunny" : "Sunscreen and hat",
    "Rain" : "Umbrella and boots",
    "Cold" : "Scarf and Gloves",
    "Default" : "Play it by ear"
}

var gear = whatToBring[weather] || whatToBring["Default"];