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

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

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

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

My top 10 JavaScript Blogs

These are the JavaScript blogs that I am repeatedly drawn to. Their emphasis is on the language itself. Real code, real situations. Enjoy!

Dmitry Baranovskiy, author of famed Raphael vector graphics engine. Updated fairly infrequently but always high quality
http://dmitry.baranovskiy.com/

Juriy Zaytsev (aka kangax) part of the Prototype.js team and all-round JavaScript good-guy. JavaScript wisdom from the master. Also best URL ever.
http://perfectionkills.com/

Alex Young et al. My first stop every morning. True to the URL – new stuff daily. Crystal clear JavaScript commentary and new product info. Added bonus – every Thursday Alex talks you through building his very own JavaScript framework.
http://dailyjs.com/

Continue reading

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

Winning Arguments

So you wanted to beef up your JavaScript utility by adding a bunch of config options and now you have a constructor with 10 arguments?

Fortunately JavaScript does not support function overloading, so you only have to supply arguments up to the last non null value. Unfortunately, if you only want to provide arguments 1, 6, 7 and 10 you also need to specify a lot of null arguments in between – and you need to count the null arguments very carefully to be certain exactly which value you are assigning to which argument. And pity anyone who is trying to read your code.

function CleverThing(element, duration, rotation, suspension, gravitation, gradation, hesitation, gestation, scale, color) {
   this.element = element;
   this.duration = duration;
   this.rotation = rotation;
   ... ...
}

var newThing = new CleverThing('arrow', null, null, null, null, 80, 200, null, null, '#FF0000' );

Object literals to the rescue. Merge all your optional arguments into one, call it something like ‘options’, and assign attributes only as required…

Continue reading