Tag Archives: javascript

How to estimate uncertain data

Data Estimator is a tool that helps answer questions about uncertain quantities, eg. “What will our company’s sales be next year?”

It is designed to be used as part of an interview process, where expert judgements are drawn out and quantified.

It’s a reminder that in this world of big data, some things remain hard to measure, especially when it comes to the future.

You will be asked a handful of questions, using “probability wheels” like this to visualise the uncertainties:

probability wheel

When you’re done, you will be able to see and export the resulting probability distribution. For example, the result could be “there is a 60% chance this market will more than double in five years, a 20% chance it will more than treble, but a 10% chance it will shrink.”

probability density

It will also show some alternatives for you how you could place the uncertainty in a decision tree, eg.

decision tree node

Try it out here: http://racingtadpole.com/more/estimator/

Dropdown menus in Meteor

I’ve been developing a site in Meteor, using their default templating engine Blaze.

And here’s a question: what’s the Meteor-like way to show a dropdown menu?

I’m using Bootstrap, so of course we can use Bootstrap’s javascript (based on jQuery) to do this. But it doesn’t feel quite right – shouldn’t we use a reactive approach, eg. with a reactive Session variable telling us whether the dropdown is open?

Surprisingly, I haven’t seen any such examples in my Google travels.

So until I get my act together to publish this as a Meteor package, here is a way to do it.

Define this html template:

<template name="dropdown">
    {{> Template.dynamic template=templateName data=templateData}}

And put this javascript in your client folder. Note it uses underscore for _.extend, but you should be able to remove this dependency if you need to.

// if the ESC key is pressed or a mouse is clicked anywhere, close any open dropdowns

$(document).keyup(function(evt) {
    if (evt.keyCode === 27) {
        Session.set('dropdown', null);

// You will need to change the word "layout" here to be a template
// that you define which covers your entire webpage
    'click': function() {
        Session.set('dropdown', null);


    "templateName": function() {
        return 'dropdown_' + this.name;

    "templateData": function() {
        // add an 'open' property to the template for the child to tell if it is open
        // _.extend(dest, src) copies all the properties in src to dest and returns dest
        return _.extend({open: Session.equals('dropdown', this.name)}, this);



    'click button': function(evt) {
        evt.stopPropagation();  // stops the full-page click handler above from firing
        Session.set('dropdown', this.name);

    'click .dropdown-menu li a': function(evt) {
        Session.set('dropdown', null);


Note that I’ve defined a click handler which fires on any click anywhere on the webpage (you need to change the line Template.layout.events to your own page-wide template), and which closes any open dropdowns. I then use evt.stopPropagation() to stop that firing when you click the button which opens the dropdown (otherwise it could never open). If you define any other click events which should not affect open dropdowns, then you need to include evt.stopPropagation() in their definition.

With that done, it’s easy to put a dropdown in your template. Just include:

{{>dropdown name='example'}}

This finds the template dropdown_example, which will have access to an “open” method to tell if it is open. So you can define it like this:

<template name="dropdown_example">
    {{#if open}}
        <ul class="dropdown-menu x">
            <li><a href="#">Option 1</a></li>
            <li><a href="#">Option 2</a></li>
            <li><a href="#">Option 3</a></li>
        <button class="invisible btn">Try this</button>
        <button class="btn">Try this</button>

If you need to pass the dropdown menu template some data, you can pass it directly:

{{>dropdown name='example' someData='foo'}}

and then dropdown_example will have access to the variable someData.

Hope that helps! If you have a better solution, or find any mistakes, please let me know.

Testing React components with Jest

Jest makes a bold claim to be “Painless Javascript Unit Testing”. I’m looking forward to using it, but it hasn’t quite lived up to that claim for me yet. Hopefully this post will help it do so for you.

If you just want a finished example, check out the tests in react-dropdown-input.

Choose the right version of node and jest

On my Mac, the latest version of jest (0.4.0) doesn’t run with the latest version of node (0.12.0). With node 0.10.37, it only works intermittently – sometimes saying:

dyld: lazy symbol binding failed: Symbol not found: _node_module_register
Expected in: dynamic lookup

and sometimes saying:

Error: Worker process exited before responding! exit code: null, exit signal: SIGSEGV (or SIGTRAP)
A worker process has quit unexpectedly! This is bad news, shutting down now!

The solution is to use jest version 0.2.1 with node 0.10.x. Hopefully future versions of jest will overcome this.

Note that the latest version of Babel seems to require node 0.12.x.

jest.dontMock is not recursive

I am testing a component called DropdownInput, built on top of React-Bootstrap, eg for DropdownInput.js:

    var ReactBootstrap = require('react-bootstrap');
    var Input = ReactBootstrap.Input;
    var DropdownMenu = ReactBootstrap.DropdownMenu;
    // in render function: 
      return (
          <Input .... />

I wrote a test like this (in __tests__.DropdownInput-test.js):

    var React = require('react/addons');
    var DropdownInput = require('../DropdownInput');
    var TestUtils = React.addons.TestUtils;
    describe('DropdownInput', function() {
      it('contains the test class', function() {
        var elt = (<DropdownInput menuClassName='test'/>);
        var renderedItem = TestUtils.renderIntoDocument(elt);
                                renderedItem, 'test');

This could not find any DOM elements with the class test:

Error: Did not find exactly one match (found: 0) for class:test

The reason is that while jest.dontMock('../DropdownInput') uses the real DropdownInput, it does not use the real ReactBootstrap components. Which is fair enough. So you need to add:


But that’s not enough! The reason is that ReactBootstrap contains the line require('classnames'), which help it put class names on its components; but jest is still mocking classnames. So you need to also add:


Happily, that does the job. It feels fragile though, because I don’t care what packages ReactBootstrap uses, as long as it works. If the author of ReactBootstrap changes which packages it uses, I don’t want all my tests breaking! Is there a better way?

There is a discussion of the pros and cons of jest’s approach to mocking here.

Shallow and deep rendering

There’s a good argument that your component tests should not try to test the subcomponent behavior anyway. In that case, you might be happy with a ‘shallow’ test like this:

    // __tests__/DropdownInput-shallow-test.js
    // Check it has the right components

    var React = require('react/addons');
    var DropdownInput = require('../DropdownInput');
    var ReactBootstrap = require('react-bootstrap');
    var TestUtils = React.addons.TestUtils;
    describe('DropdownInput', function() {
      var menuClassName = 'test';
      var elt = (<DropdownInput menuClassName={menuClassName}/>);
      var result;

      beforeEach(function() {
        var shallowRenderer = TestUtils.createRenderer();
        result = shallowRenderer.getRenderOutput();

      it('contains the right components', function() {
        // for now, assume in that order - TODO: generalize
        var child0 = result.props.children[0];
        var child1 = result.props.children[1];
        // and check the menu is passed the right class name

      it('contains the right first menu item', function() {
        // again, not a very general approach
        var child1 = result.props.children[1];
        var child1props = child1.props.children[0];


And this works nicely. However, as it is written, it assumes a lot about the structure of the component, like what order the elements are in. If I decide to wrap my component in an extra div for some reason, it will break my tests. Is there an equivalent to TestUtils.findRenderedDOMComponentWithType that we can use for shallow rendering, so I don’t have to assume ordering?

But you could also argue the opposite case: that the tests shouldn’t care how DropdownInput produces the desired behavior, only that it does – ie. it should test the behavior, not which components it uses. For this you need a ‘deep’ test, with lots of the mocking turned off. Eg:

    // __tests__/DropdownInput-deep-test.js
    // Check it has the right behavior
    var React = require('react/addons');
    var DropdownInput = require('../DropdownInput');
    var ReactBootstrap = require('react-bootstrap');
    var TestUtils = React.addons.TestUtils;

    describe('DropdownInput', function() {
      var menuClassName = 'test';
      var elt = (<DropdownInput menuClassName={menuClassName}/>);
      var renderedItem;

      beforeEach(function() {
        renderedItem = TestUtils.renderIntoDocument(elt);

      it('has a working input', function() {
        var txt = 'a';
        var input = TestUtils.findRenderedDOMComponentWithTag(
                        renderedItem, 'input').getDOMNode();
        //TestUtils.Simulate.keyDown(input, {key: 'a'});  // this doesn't work
        TestUtils.Simulate.change(input,  {target: {value: txt}});


And this works nicely too, except that the test needs to know which packages to unmock. (And why doesn’t Simulate.keyDown work?)

So, at this early stage in my jest career, I plan to include both sorts of tests for each component, in separate files.

Flux components

If you’re using the Flux architecture, then user interaction will often fire an action, rather than directly changing the DOM. So instead of testing the DOM directly, we need to test that an action was sent. To do this, I adapted the tutorial on Testing Flux Applications (which describes testing stores), as follows:

    var element,

    describe('MyComponent', function() {

        beforeEach(function() {
          // by requiring a new copy for every test, 
          // we reset the mock call counters for each test
          MyComponent = require('../my-component.js');
          ActionCreators = require('../../../actions/action-creators');
          // Render it
          element = <MyComponent />;  // include relevant props
          cpt = TestUtils.renderIntoDocument(element);
          rendered = TestUtils.findRenderedDOMComponentWithTag(cpt, 'div');
          // note - this version doesn't work - why??
          // rendered = TestUtils.findRenderedComponentWithType(cpt, MyComponent);

        it('clicking on it sends the right action', function() {
          // first check that no action calls were made yet
          // ActionCreators.myAction is the desired action
          var actionCalls = ActionCreators.myAction.mock.calls;
          // Simulate a click and verify that it sends out the action
          // check it sent the right params (replace ... with args)

(You won’t find this in the DropdownInput component tests, since it doesn’t fire any actions.)


I hope this saves you some time and development pain. Please let me know if you have better solutions to any of these issues!

The working DropdownInput component and tests are available at github.com/RacingTadpole/react-dropdown-input; you can see also a demo here.

Flux & React Best Practices

So, you want to start a new javascript project using React, perhaps using the Flux architecture. Excellent! But you’re not quite sure where to begin. Well, actually, you know where to begin, but you’ve quickly hit a barrage of design questions. Should that API call go in the store, the view component, or the action creator? Should I store that data in a state or pass it down from a parent component through props? How should I update the view before I receive that ajax data? And so on.

Here are some helpful tips which can guide you along the way. I am no authority on React, so I have included references to those who are. Please leave a comment if you think there are better ways.

Components & State

Try to keep as many of your components as possible stateless.

A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props.

State should contain data that a component’s event handlers may change to trigger a UI update.


Ajax APIs

In Flux, all ajax API calls should come from the action creators.

paraphrased from http://facebook.github.io/flux/docs/chat.html

In response, the API fires actions on success (eg. “receive data”) or failure (eg. “receive error”).

For example, ViewActionCreators.js:

// ViewActionCreators.js
var AppAPI = require('../apis/AppAPI');
var ViewActionCreators = {
  doSomething: function(something) {
      actionType: AppConstants.DO_SOMETHING,
      something: something
    // fire off API call


// AppAPI.js
// this example uses jQuery's ajax call
var ServerActionCreators = require('../actions/ServerActionCreators');
function post(url) {
  $.ajax({url: url
    success: function(data) {
    error: function(xhr, status, err) {
      ServerActionCreators.receiveAPIError({ err: err });


// ServerActionCreators.js
var ServerActionCreators = {
  receiveData: function(data) {
      actionType: AppConstants.RECEIVE_DATA,
      data: data
  receiveAPIError: function(err) {
      actionType: AppConstants.RECEIVE_API_ERROR,
      err: err

In this code, the user interacts with the view, which fires the DO_SOMETHING action. That action itself fires off the API call, and when the API call is done it sends either a RECEIVE_DATA or a RECEIVE_API_ERROR action, which the Store can listen for. (As we’ll see below, the Store may listen for DO_SOMETHING too.)

These snippets are based on the Flux demo Chat app.

It seems there is one exception to the rule that only Action Creators call the API: loading initial data. This can go directly in the view controller. See https://facebook.github.io/react/tips/initial-ajax.html for an example.


Stores should remain as independent and decoupled as possible — a self-contained universe that one can query from a Controller-View.
The only road into the Store is through the callback it registers with the Dispatcher. The only road out is through getter functions.
Stores also publish an event when their state has changed, so Controller-Views can know when to query for the new state, using the getters.


Stores should only execute synchronous code. Otherwise they are too hard to understand.



If you’re using Flux, you should start writing your stores using immutable-js.

If we also use immutable-js data structures to hold the components’ state, we could mix PureRenderMixin into all our components and short circuit the re-rendering process.


Here is how I’ve done it. In the Store, make changes like this:

var Immutable = require('immutable');
var selected = Immutable.List();  // was: var selected = [];
// ...
selected = selected.push(item);  // was: selected.push(item);
// ...
selected = selected.delete(i);   // was: selected.splice(i, 1);
// ...
// I receive a js array of js objects from the API
// and convert to immutable list of immutable maps: 
  var tmp = myArray.map(function(item) {
    return Immutable.Map(item);
  return Immutable.List(tmp);
// ...

In the Component, there are not many changes required – I don’t even require('immutable') in this example. The changes arise just because the objects returned by the Store are no longer plain old javascript objects, but immutable ones.

var React = require('react/addons');
var PureRenderMixin = React.addons.PureRenderMixin;

// no change needed state-setting function if it's like:
function getMyState() {
  return {
    a: MyStore.getSelected(),
    b: MyStore.getOther()

  mixins: [PureRenderMixin],      // add this
  // no change to these, eg.
    return getMyState();
  _onChange: function() {  // ChangeListener callback
  // ...
var num = this.state.a.count();  // was this.state.a.length 
// maybe other small changes due to API differences

Here is an example of the ToDo app rewritten with Flux and immutablejs.

The React documentation also refers to another immutability helper, update(). This uses ordinary Javascript objects, whereas immutablejs uses its own object types. I have decided to use immutablejs, but please tell me if you have a way to do it with update.

Optimistic Updates

While waiting for an ajax API to return, you often want to optimistically update the UI. I’ve settled on the following pattern to do this:

  • Optimistically update the Store. Do not bypass the store by only saving it in the component state.
  • This means you will update the same Store data twice: once based on the user action, and then again based on the received API action (or API error action).
  • If you need to know if the API action has completed, you can set another variable (eg. optimistic) to track that, along with a getter function that the component can listen for. I’m using this to display a spinner while some data loads.

I tried doing each of these on its own too, but then you either can’t easily update the view optimistically, or you get a messy chain of actions.

The potential downsides are:

  • There could be other reasons for the API actions being received
  • I’m not sure I want this store to know about the API-generated actions (though the alternative still needs the API error action)
  • What if an API call is not required, and the data comes from somewhere else?

Reacting to non-React events

Attach generic DOM events (eg. window resizing) to componentDidMount. This is well explained at http://facebook.github.io/react/tips/dom-event-listeners.html

In the window resizing example, note they do not attempt to keep the current window size in a Store. Instead, it is kept in the component’s state. It would be complicated to keep a Store synched up with window.innerWidth, which is anyway the ultimate truth here.

Testing components

It took me a while to get Jest tests working, due to a combination of version conflicts, trouble understanding the nature of auto-mocking, and then deciding which things to mock. I’ve written up a separate post on unit testing components.

Other resources

Here are some resources (well, one anyway) that helped me get going:

Curve fitting with javascript & d3

If javascript is up to amazing animations and visualizations with d3, maybe it’s up to non-linear curve fitting too, right?

Something like this, perhaps:

Here’s how I did it:

  • The hard work is done using Cobyla (“Constrained Optimization BY Linear Approximation”), which Anders Gustafsson ported to Java and Reinhard Oldenburg ported to Javascript, as per this stackoverflow post.
    Cobyla minimises a non-linear objective function subject to constraints.
  • The demo and its components (including cobyla) use the module pattern, which has the advantage of keeping the global namespace uncluttered.
  • To adapt Cobyla to this curve fitting problem, I wrote a short wrapper which is added onto the cobyla module as cobyla.nlFit(data, fitFn, start, min, max, constraints, solverParams). This function minimises the sum of squared differences (y1^2-y2^2) between the data points, (x,y1), and the fitted points, (x,y2).
  • The Weibull cumulative distribution function (CDF), inverse CDF and mean are defined in the “distribution” module. Thus distribution.weibull([2,1,5]) .inverseCdf(0.5) gives the median (50th percentile) of a Weibull distribution with shape parameter 2, scale parameter 1 and location parameter 5.
  • The chart is built with d3. I am building an open-source library of a few useful chart types, d3elements, which are added onto the d3 module as d3.elts. This one is called d3.elts.xyChart.
  • So the user interface doesn’t get jammed, I use a javascript web worker to calculate the curve fit. I was surprised how easy it was to set this up.
  • I apologise in advance that this sample code is quite complicated. If you see ways to make it simpler, please let me know.
  • Finally, this may be obvious, but I like the rigour that a tool like jshint imposes. Hence the odd comment at the top of fitdemo.js, /* global fitdemo: true, jQuery, d3, _, distribution, cobyla */

Check out the source code on bitbucket here. You can see it being used for uncertain data estimation here.

Please let me know what you think!

D3 Time Series Chart with Zoom & Notes

This is an example of a reusable chart built using d3. The range (zoom) slider and the notes panel are also built in d3, as separate widgets, so they can be customized further.

Check the sample source code on bitbucket for the full description of how to use it; here is the essence (without notes):

    var rangeWidget = d3.elts.startEndSlider().minRange(365*24*3600*1000);
    var tsChart = d3.elts.timeSeriesChart().rangeWidget(rangeWidget);
    d3.csv('data.csv', function(data) {
        tsData = _.map(data, function(d) {return [d.date, d.price]});

To add notes to this, use:

    var rangeWidget = d3.elts.startEndSlider().minRange(365*24*3600*1000);
    var clickPanel = d3.elts.makeClickPanel();
    var tsChart = d3.elts.timeSeriesChart().rangeWidget(rangeWidget);
    tsChart.notesMarkerClick(function(elt, note, closer) {
        clickPanel(elt, note && ("<h3>"+note.title+"</h3><p>"+note.desc+"</p>")), closer);
    d3.csv('data.csv', function(data) {
        d3.csv('wheatNotes.csv', function(notes) {
            tsData = _.map(data, function(d) {return [d.date, d.price]});

As an alternative approach, check out this block from Mike Bostock for a way to pan and zoom using d3′s brush control.

Hope you find it useful!

Visualising Flows in a D3 Chord Diagram with Hover

This is an example of a reusable chart built using d3.

The idea is that you have a matrix of the flows between one category (here, optimist/neutral/pessimist) to another (introvert/extrovert). `d3.elts.flowChord()` then converts this matrix into a chord diagram, with the option of hover text.

Check the sample source code on bitbucket for the full description of how to use it; here is the essence:

  var colors = d3.scale.ordinal().range(["#AAA", "steelblue", "green", "orange", "brown"]);
  var hoverHtml = {'Introvert': '<h1>Introverts</h1>Like to be by themselves', 
      'Extrovert': '<h1>Extroverts</h1>Like the company of other people', 
      'Optimist': '<h1>Optimists</h1>Look on the bright side of life',
      'Neutral': '<h1>Neutrals</h1>Life could be good, it could be bad',
      'Pessimist': '<h1>Pessimists</h1>See the glass half empty'}
  var chordDiagram = d3.elts.flowChord().colors(colors).hoverHtml(hoverHtml).rimWidth(30);
  var data = [['Disposition','Optimist','Neutral','Pessimist'],
              ['Introvert', 0.8, 0.4, 0.67], 
              ['Extrovert', 0.2, 0.6, 0.33]]

Experience with Meteor

Meteor Day is upon us!

Here are the slides I am going to present on my experience developing with Meteor. In a nutshell -

  • Love the principles – they made it easy to develop a great webapp quickly
  • I’ve done a few cool things, I think! (like encryption, undo, admin panel with datatables, custom art:accounts-ui)
  • But… SEO is killing me (only two keywords showing!?)
  • The Paypal IPN has been a pain – still unresolved
  • Can’t escape the usual browser issues – and Iron Router adds a few for IE9
  • Speed has been an intermittent problem
  • Still feeling my way towards a good programming style
  • Please check out the app!
(Just click on the slide above and then you can advance through the deck using the arrow keys. Alternatively, click here to see them in a new tab.)

You can see the slides from the talk online here.


Harness your Python style to write good Javascript

Python encourages you to write good code. Javascript does not. How can you harness your Python style to write good Javascript?


Let’s try to write this Python code in Javascript.

class Vehicle(object):
    def __init__(self, size):
        self.size = size
    def __str__(self):
        return "Vehicle of size {0}".format(self.size)

class Hovercraft(Vehicle):
    def __init__(self, *args, **kwargs):
        # initialize just like a vehicle
        super(Hovercraft, self).__init__(*args, **kwargs)
        # add extra custom init if needed
    def hover(self, height):
        print("Hovering at height {0}".format(height))

# eg. make a new size 8 hovercraft
h = Hovercraft(8)
# eg. hover at height 12
# eg. change size and print
h.size = 9

Not obvious? The problem is that Javascript doesn’t have an out-of-the-box analogue to classes. Somehow we need to adapt objects and functions to the task.

Use prototypes

Your first thought might be to define new object types by defining object constructors, which are called with the new keyword, and adding methods to the object’s prototype chain. These objects look a lot like classes, don’t they? So you might write something like this:

// Not the best approach - see below
function Vehicle(size) {
    this.size = size;
    // or use this and arguments pseudo-arguments
Vehicle.prototype.toString = function () {
    return "Vehicle of size " + this.size;
function Hovercraft(size) {
    this.size = size;
Hovercraft.prototype = new Vehicle();
Hovercraft.prototype.hover = function (height) {
    alert("hovering at height "+height);

// eg. make a new size 8 hovercraft
h = new Hovercraft(8);
// eg. hover at height 12
// eg. change size and print
h.size = 9

This has a number of problems:

  • Vehicle and Hovercraft have the same constructor, but you can’t reuse it.
  • It feels strange to define the class’s methods outside the constructor, with the prototype lines.
  • There’s no room for private variables or methods.

Use closures

For a better solution, we need to think laterally – and use Javascript’s closures. I was hesitant to make use of these at first, thinking it would only lead to perverse and impenetrable code. But in fact they are a force for good, as we’ll see.

Put simply, a closure is a function which has variables bound to it. You write the closure as a function inside another function. The trick is that the inner function can refer to any of the outer function’s local variables. (Thanks for this succinct summary StackExchange!)

Here’s a nice example of a closure from a talk on functional programming given by Douglas Crockford, JavaScript architect at PayPal and formerly Yahoo (at 57mins). (In fact the previous example is from this talk too.) In this example, a closure is used to produce an object called singleton, which has a private variable, a private function, and two methods. You call the two methods as singleton.firstMethod(a,b) and singleton.secondMethod(c):

var singleton = (function () {
    var privateVariable;
    function privateFunction(x) {

    return {
        firstMethod: function (a, b) {
        secondMethod: function (c) {
}() );
// note the function is called immediately,
// so the var singleton is its returned value
// the surrounding brackets are just to help the reader

So let’s adapt that to our problem:

function vehicle(size) {
    var that = {
        size: size,
        toString: function () { 
            return "Vehicle of size " + this.size; 
    return that;
function hovercraft(size) {
    var that = vehicle(size);  // inherit from vehicle
    that.hover = function(height) { 
        alert("hovering at height "+height);
        return that; // optional - allows chaining
    return that;

// eg. make a new size 8 hovercraft
h = hovercraft(8);
// eg. hover at height 12
// eg. both at once using chaining
g = hovercraft(8).hover(12);
// eg. change size and print
h.size = 9

In the above, size is accessible to the world, just as it is in Python. But Javascript also lets us make it private:

function vehicle(size) {
    // can define private variables here
    // instead, here we use the fact that parameters are private
    return {
        toString: function () { 
            return "Vehicle of size " + size; 

In general, to make your own constructor function (eg. vehicle, hovercraft), you follow this recipe from the talk:

  1. Make an object
  2. Define (private) variables and functions
  3. Augment the object with methods (which have access to the privates above)
  4. Return the object

This pattern has a name: the module pattern. You’ll find a great writeup of it, and some ways to use it across multiple js files, in this post by Ben Cherry. He also points out the best way to handle dependencies, and to update existing variables.

Use chaining

In the example above, I have added the extra feature of “chaining”. In Python you have to put each effect on a separate line, eg.:

h.size = 9

But in Javascript you can potentially chain it all together into one, like so:


I first discovered the joy of chaining while using Mike Bostock’s super-powerful D3 library. He describes how to do it here – in fact, his description of how to write a reusable chart arrives at the same closure-based solution as we have, with the addition of getters and setters as below.

We made hover chain, but size do it doesn’t yet, as it’s a variable, not a function. Mike solves this by adding a getter/setter function for each public variable, which we could add like this:

function vehicle(startSize) {
    var size = startSize;
    var that = {
        toString: function () { 
            return "Vehicle of size " + size;
    // getter/setter functions
    that.size = function(_) {
        if (!arguments.length) return size;
        size = _;
        return that; // Q: would 'return this' work?
    return that;
// eg. this works now

Then h.size() returns (gets) the hovercraft h‘s size, and h.size(9) sets the size to 9.

Another benefit: the code never refers to this. That’s handy, because I find whenever I refactor code into smaller functions I get tripped up by the meaning of this changing.

You may also recognize such getters and setters from jQuery, where eg. $("body").text() returns the page body’s text, and $("body").text("eels") sets the body’s text to “eels”.

Still, as nice as chaining is, needing to add 5 lines of boilerplate code for every variable, with 3 references to the variable name that must be changed each time, is the sort of thing we became programmers to avoid.

To solve this, I am starting to put all the variables with getters and setters into a single object, eg. xt:

function vehicle(startSize) {
    var ext = {size: startSize};
    if (Object.keys) {
        var extKeys = Object.keys(ext);
    function toString() {
        return "Vehicle of size " + ext.size;
    return {
        toString: toString,
        get: function(name) {
            if (!arguments.length) return ext;
            return ext[name];
        set: function(name, val) {
            if (typeof extKeys!=="undefined" && extKeys.indexOf) {
                if (extKeys.indexOf(name)>=0) {
                    ext[name] = val;
                } else {
                    throw Error("Variable "+name+" not found");
            } else {
                // on browsers without Object.keys or indexOf,
                // don't check the name is valid
                ext[name] = val;
            return this;
// eg. these work

Don’t make it a global

Finally, you probably don’t want to have a new global called vehicle. It’s better to add it to another module, eg. RT (which may or may not already exist), as RT.vehicle. It might also depend on other modules, eg. the underscore (_) library. To do this, wrap the whole function in another closure!

if (typeof _ === 'undefined') { 
    throw new Error('Vehicle requires underscore') 
(function(RT, _) {
    function vehicle(startSize) { 
        ... // copy from above

    // attach vehicle to RT
    if (typeof RT==="undefined") {
        RT = {};
    RT.vehicle = vehicle;
    return RT;
}(typeof RT === "undefined" ? {} : RT, _));
// eg. make a new size 9 vehicle
v = RT.vehicle(9);

Too crazy?

In conclusion

Javascript’s closures give you access to some interesting programming patterns. Foremost among them, it lets you implement Python-style classes, with the added bonus of private variables and functions. And this is not just an academic gimmick that risks complicating your code in the real world: it is championed by the people who develop javascript, and it is used by jQuery and D3 among others. It helps you to write good, reusable code.

So – please let me know if you’ve used this pattern before, and whether my comparison to Python’s classes stacks up.

A final thought – perhaps it is wrong to compare Javascript to Python after all. Perhaps it is better compared to LISP!