Mark Dalgleish

Mark Dalgleish

UI Engineer - Melbourne, Australia

A Touch of Class: Inheritance in JavaScript

The object-oriented features of JavaScript, such as constructors and prototype chains, are possibly the most misunderstood aspects of the language. Plenty of people who have been working full time with JavaScript still struggle with these concepts, and I argue that this is purely a result of its confusing, Java-style syntax.

But it doesn’t have to be this way. Hiding beneath the “new” keyword is a rich and elegant object model, and we’ll spend some time coming to grips with it.

By seeing how simple inheritance in JavaScript can be if we use more modern syntax, we’ll be able to better understand the unfortunate syntax we’ve been stuck with from the beginning.

JavaScript’s lack of class

The biggest act of misdirection in JavaScript is that it looks like it has classes. When someone is new to JavaScript, particularly if they come from another language that does have classes, they might be surprised to find code like this:

1
var charlie = new Actor();

Which leads to quite possibly the biggest surprise people face when trying to come to grips with JavaScript: it doesn’t have classes. You might assume that elsewhere in the code is the class definition for “Actor”, but instead you find something like this:

1
2
3
4
5
6
7
function Actor(name) {
    this.name = name;
}

Actor.prototype.act = function(line) {
    alert(this.name + ': ' + line);
};

From here it only gets worse when multiple inheritance is involved:

1
2
3
4
5
6
7
8
9
10
function Actor(name) {
    this.name = name;
}
Actor.prototype.canSpeak = true;

function SilentActor() {
    Actor.apply(this, arguments);
}
SilentActor.prototype = new Actor();
SilentActor.prototype.canSpeak = false;

Sometimes despite years of experience, even those who realise that JavaScript doesn’t have classes may still find themselves never quite grasping the concepts behind such cryptic syntax.

Taking a step back

To put these decisions in the proper historical context, we need to take a trip back to the year 1995. Java was the hot new web language, and Java applets were going to take over the world.

We all know how this story ends, but this was the environment in which Brendan Eich was toiling away at Netscape on his “little” web scripting langauge.

This cultural pressure resulted in some rebranding. What was originally “Mocha”, then “LiveScript”, eventually became known as “JavaScript”. While it may have eventually extended beyond its original scope, Brendan Eich wasn’t shy about pitching it as Java’s little brother.

It’s just a prototype

The problem, of course, is that despite JavaScript’s syntactic similarities to Java, its conceptual roots lay elsewhere. A dynamically typed language, it borrowed functional aspects from Scheme, and prototypal inheritance from Self.

In classical languages, like Java, instances are created from classes. JavaScript differs in that it has prototypal inheritance, in which there are no classes.

Instead, objects inherit from other objects.

Modern inheritance

To best understand the concepts behind prototypal inheritance, you must unlearn what you have learned. You’ll find it is much easier to appreciate object-to-object inheritance if you pretend you’ve never seen JavaScript’s misleading, classically-styled syntax.

In ECMAScript 5, the latest version of JavaScript available in all modern browsers (Chrome, Firefox, Safari, Opera, IE9+), we have new syntax for creating object-to-object inheritance, based on Douglas Crockford’s original utility method for simple inheritance:

1
var childObject = Object.create(parentObject);

If we use Object.create to recreate our ‘SilentActor’ example from earlier, it becomes much easier to see what’s really going on:

1
2
3
4
5
6
7
8
9
10
11
12
// Our 'actor' object has some properties...
var actor = {
  canAct: true,
  canSpeak: true
};

// 'silentActor' inherits from 'actor'
var silentActor = Object.create(actor);
silentActor.canSpeak = false;

// 'busterKeaton' inherits from 'silentActor'
var busterKeaton = Object.create(silentActor);

In modern browsers, we also have a new method for reliably inspecting the prototype chain:

1
2
3
Object.getPrototypeOf(busterKeaton); // silentActor
Object.getPrototypeOf(silentActor); // actor
Object.getPrototypeOf(actor); // Object

In this simple example, we’ve been able to set up a prototype chain without using a single constructor or “new” keyword.

Walking the chain

So how does a prototype chain work? When we try to read a property from our new ‘busterKeaton’ object, it checks the object itself and, if it didn’t find the property, it traverses up the prototype chain, checking each of its prototype objects in order until it finds the first occurence of the property.

All this happens when we ask for the value of a property from an object.

1
busterKeaton.canAct;

In order to properly evaluate the value of ‘canAct’ on ‘busterKeaton’, the JS engine does the following:

  1. Checks ‘busterKeaton’ for the ‘canAct’ property, but finds nothing.
  2. Checks ‘silentActor’, but doesn’t find the ‘canAct’ property.
  3. Checks ‘actor’ and finds the ‘canAct’ property, so returns its value, which is ‘true’.

Modifying the chain

The interesting thing is that the ‘actor’ and ‘silentActor’ objects are still live in the system and can be modified at runtime.

So, for a contrived example, if all silect actors lost their jobs, we could do the following:

1
2
3
4
silentActor.isEmployed = false;

// So now...
busterKeaton.isEmployed; // false

Where’s “super”?

In classical languages, when overriding methods, you can run the method from the parent class in the current context.

In JavaScript we have even more options: we can run any function in any context.

How do we achieve this? Using JavaScript’s ‘call’ and ‘apply’ methods which are available on all functions. Appropiately enough, these are available because they exist on the ‘Function’ prototype.

They both allow us to run a function in a specific context which we provide as the first parameter, along with any arguments we wish to pass to the function.

Using our ‘silentActor’ example, if we want to achieve the equivalent of calling ‘super’, it looks something like this:

1
2
3
4
5
6
7
8
actor.act = function(line) {
    alert(this.name + ': ' + line);
}

silentActor.act = function(line) {
    // Super:
    actor.act.call(this, line);
};

If it took multiple arguments, it would look like this:

1
2
3
4
5
6
7
silentActor.act = function(line, emotion) {
    // Using 'call':
    actor.act.call(this, line, emotion);

    // Using 'apply':
    actor.act.apply(this, [line, emotion]);
};

Where are the constructors?

With this setup, it is quite simple for us to create our own DIY constructor:

1
2
3
4
5
6
7
8
9
10
function makeActor(name) {
    // Create a new instance that inherits from 'actor':
    var a = Object.create(actor);

    // Set the properties of our instance:
    a.name = name;

    // Return the new instance:
    return a;
}

Understanding prototypes with a touch of class

Now that we’ve seen how simple object-to-object inheritance can be, it’s time to look at our original example again with fresh eyes:

1
var charlie = new Actor();

‘Actor’ is, obviously, not a class. It is, however, a function.

It could be a function that does nothing:

1
function Actor() {}

Or, it could set some properties on the new instance:

1
2
3
function Actor(name) {
    this.name = name;
}

In our example, the ‘Actor’ function is being used as a constructor since it is invoked with the “new” keyword.

The funny thing about JavaScript is that any function can be used as a constructor, so there’s nothing special about our ‘Actor’ function that makes it different from any other function.

Clarifying “constructors”

Since any function can be a constructor, all functions have a ‘prototype’ property just in case they’re used as a constructor. Even when it doesn’t make sense.

A perfect example is the ‘alert’ function, which is provided by the browser. Even though it’s not meant to be used as a constructor (in fact, the browser won’t even let you), it still has a ‘prototype’ property:

1
2
3
typeof alert.prototype; // 'object'

new alert(); // TypeError: Illegal invocation

When ‘Actor’ is used as a constructor, our new ‘charlie’ object inherits from the object sitting at ‘Actor.prototype’.

Functions are objects

If you missed that, let me re-iterate. Functions are objects, and can have arbitrary properties.

For example, this is completely valid:

1
2
3
4
5
function Actor(){}

// We can set any property:
Actor.foo = 'bar';
Actor.abc = [1,2,3];

However, the ‘prototype’ property of a function is where we store the object that all new instances will inherit from:

1
2
3
4
5
6
7
function Actor(){}

// Used for constructors:
Actor.prototype = {foo: 'bar'};

var charlie = new Actor();
charile.foo; // 'bar'

Creating the chain

Setting up multiple inheritance with our class-like syntax should now be a bit easier to grasp.

It’s simply a case of making a function’s ‘prototype’ property inherit from another function’s ‘prototype’:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Set up Actor
function Actor() {}
Actor.prototype.canAct = true;

// Set up SilentActor to inherit from Actor:
function SilentActor() {}
SilentActor.prototype = Object.create(Actor.prototype);

// We can now add new properties to the SilentActor prototype:
SilentActor.prototype.canSpeak = false;

// So instances can act, but can't speak:
var charlie = new SilentActor();
charlie.canAct; // true
charlie.canSpeak; // false

Construction: Just 3 simple steps

At this point, it’s important to point out what’s going on inside a constructor. Instantiating a new object with a “constructor” performs three actions and, as an example, let’s take a look at what happens with our ‘Actor’ constructor:

1
var charlie = new Actor();

This one line of the code does the following:

  1. Creates a new object, ‘charlie’, that inherits from the object sitting at ‘Actor.prototype’,
  2. Runs the ‘Actor’ function against ‘charlie’, and
  3. Returns ‘charlie’.

Coming full circle

You might think that this sounds awfully familiar because this precisely mirrors the steps in our “DIY constructor” from earlier, which looked like this:

1
2
3
4
5
6
7
8
9
10
function makeActor(name) {
    // Create a new instance that inherits from 'actor':
    var a = Object.create(actor);

    // Set the properties of our instance:
    a.name = name;

    // Return the new instance:
    return a;
}

Just like our earlier example, asking our ‘busterKeaton’ object for the ‘canAct’ property will walk up the prototype chain, except this time the JS engine will act slightly differently:

  1. Checks ‘busterKeaton’ for the ‘canAct’ property, but finds nothing.
  2. Checks ‘SilentActor.prototype’, but doesn’t find the ‘canAct’ property.
  3. Checks ‘Actor.prototype’ and finds the ‘canAct’ property, so returns its value.

You’ll notice that the chain now consists of objects sitting at the ‘prototype’ property of functions, each of which had been used as the object’s constructor.

Keeping it classic

Even after understanding the syntax, it’s still common for people to want to get as far away from it as possible.

There are implementations of “classical” inheritance built on top of JavaScript’s prototypal inhertance, the most notable of which is John Resig’s famous “Class” function.

You’ll also find a lot of languages that compile to JavaScript, such as CoffeeScript or TypeScript, offer standard class syntax. TypeScript in particular ensures it closely resembles the draft ECMAScript 6 class specification.

Yes, the ES6 specification draft contains “class” sugar which, like CoffeeScript and TypeScript, is really prototypal inheritance under the hood.

Clearing the air

Of course none of the classical misdirection and shim layers can really replace a true understanding of prototypal inheritance and the power it affords you.

Hopefully this article has helped clear things up for you and, if you still find yourself puzzled, I hope at the very least that the next time you dig into prototypal inheritance, your mind will have been sufficiently prepared for thinking like Brendan Eich did all those years ago.

If not, there’s always Java applets.

Slides from Web Directions South 2012

This article is based on a presentation I gave on 18 October, 2012 at Web Directions South in Sydney, Australia. The slides are available online.

Mobile Parallax With Stellar.js

Parallax effects can be an extremely effective way to engage users during the simple act of scrolling. What is normally a simple process of moving static content along the screen can become an act of moving through a makeshift, HTML world. While the effect can certainly be abused, when applied with a light, elegant touch, it can breathe new life into your site.

Unfortunately this effect is hampered on touch devices, where tactile feedback and intertial scrolling would perfectly suit parallax animation. Mobile browsers place a limit on script execution during scroll, so your carefully crafted parallax effects won’t happen until scrolling has come to a complete halt. As you can imagine, this is far from impressive.

As a personal goal to not only make parallax effects as simple as possible, but to make them work on mobile browsers where these effects are notoriously difficult, I created a scrolling parallax library called Stellar.js.

If you’re feeling impatient, you can skip straight to the demo. At this point, you might be wondering what the issue with mobile browsers happens to be, and how Stellar.js lets us overcome this.

The overflow problem

When we got our first taste of HTML5-capable mobile browsers, one of the first things web designers and developers noticed was their lack of scrolling overflow support.

On desktop we took it for granted that we could add a scroll bar to any element. This ability was taken away from us on these new platforms which, inside their own native applications, commonly made use of small, nested scrolling panes in order to better fit more content on such relatively tiny screens.

Plenty of people noticed this shortcoming, and some library authors weren’t ready to be defeated.

Enter touch scrolling libraries

It didn’t take long for some smart developers to find ways around this limitation by creating libraries which emulate native scroll using CSS3 transforms.

While their need is somewhat dimished with the overflow-scrolling property, they still prove vital for overcoming our JavaScript issues. By emulating native scroll, the browser no longer throttles our script execution.

There’s quite a few to choose from, and all of these will integrate with Stellar.js:

Before we use one of these libraries, we first need to create a standard, non-mobile parallax example.

Marking up a simple desktop-only demo

To get started, we need a basic HTML page with jQuery, Stellar.js and some parallax elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!doctype html>
<html>
  <head>
      <title>Mobile Parallax with Stellar.js - Demo</title>
      <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>

      <h1>Stellar.js</h1>
      <h2>Mobile Parallax Demo</h2>
      <p>Scroll down to see Stellar.js in action.</p>
              
      <section>
          <div class="pixel" data-stellar-ratio="1.1"></div>
          <div class="pixel" data-stellar-ratio="1.2"></div>
          <div class="pixel" data-stellar-ratio="1.3"></div>
          <div class="pixel" data-stellar-ratio="1.4"></div>
          <div class="pixel" data-stellar-ratio="1.5"></div>
          <div class="pixel" data-stellar-ratio="1.6"></div>
          <div class="pixel" data-stellar-ratio="1.7"></div>
          <div class="pixel" data-stellar-ratio="1.8"></div>
          <div class="pixel" data-stellar-ratio="1.9"></div>
          <div class="pixel" data-stellar-ratio="2.0"></div>
      </section>

      <script src="jquery.min.js"></script>
      <script src="jquery.stellar.min.js"></script>
      <script src="script.js"></script>
  </body>
</html>

A couple of files are referenced here which haven’t been created yet: “script.js” and “style.css”.

Scripting and styling

The code in script.js initialises Stellar.js, which activates all elements with data-stellar-ratio data attributes:

1
2
3
4
5
6
$(function(){
  $.stellar({
    horizontalScrolling: false,
    verticalOffset: 150
  });
});

In style.css we specify how the content should look, paying particular attention to the styling of our “pixel” elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
* {
  margin: 0;
  padding: 0;
}

body {
  background: #2491F7;
}

section {
  position: relative;
  top: 400px;
  width: 300px;
  height: 3000px;
  margin: 0 auto;
}

h1, h2, p {
  color: white;
  font-family: helvetica, arial;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
  position: absolute;
  left: 50%;
  width: 300px;
  margin-left: -150px;
}

h1 {
  font-size: 68px;
  top: 85px;
}

h2 {
  font-size: 27px;
  top: 170px;
}

p {
  font-size: 17px;
  top: 210px;
}

.pixel {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 15px;
  background: white;
}

  .pixel:nth-child(2)  { left: 30px;  }
  .pixel:nth-child(3)  { left: 60px;  }
  .pixel:nth-child(4)  { left: 90px;  }
  .pixel:nth-child(5)  { left: 120px; }
  .pixel:nth-child(6)  { left: 150px; }
  .pixel:nth-child(7)  { left: 180px; }
  .pixel:nth-child(8)  { left: 210px; }
  .pixel:nth-child(9)  { left: 240px; }
  .pixel:nth-child(10) { left: 270px; }

We now have a very basic, desktop-only parallax demo but, as you’d expect, we are going to make this work cross-platform.

Adding mobile support

We first need to make some adjustments to the markup. We need to add a mobile-friendly meta tag:

1
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />

We next need to add a couple of divs for iScroll, namely a “wrapper” div and a “scroller” div:

1
2
3
4
5
6
7
<div id="wrapper">
  <div id="scroller">

    <section>...</section>

  </div>
</div>

Finally, we need to include the JavaScript for iScroll:

1
<script src="iscroll.js"></script>

The complete HTML file now looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />
    <title>Mobile Parallax with Stellar.js - Demo</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>

    <div id="wrapper">
      <div id="scroller">

        <h1>Stellar.js</h1>
        <h2>Mobile Parallax Demo</h2>
        <p>Scroll down to see Stellar.js in action.</p>

        <section>
          <div class="pixel" data-stellar-ratio="1.1"></div>
          <div class="pixel" data-stellar-ratio="1.2"></div>
          <div class="pixel" data-stellar-ratio="1.3"></div>
          <div class="pixel" data-stellar-ratio="1.4"></div>
          <div class="pixel" data-stellar-ratio="1.5"></div>
          <div class="pixel" data-stellar-ratio="1.6"></div>
          <div class="pixel" data-stellar-ratio="1.7"></div>
          <div class="pixel" data-stellar-ratio="1.8"></div>
          <div class="pixel" data-stellar-ratio="1.9"></div>
          <div class="pixel" data-stellar-ratio="2.0"></div>
        </section>

      </div>
    </div>

    <script src="jquery.min.js"></script>
    <script src="jquery.stellar.min.js"></script>
    <script src="iscroll.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Detecting mobile devices

Now that we have iScroll available, and the required markup, we need to update our script.js file.

We’re going to be introducing some local variables that we don’t want leaking into the global scope, so our first step is to wrap our code in an immediately invoked function expression (IIFE):

1
2
3
(function(){
  // code goes here...
})();

In order to activate iScroll only when we’re on a mobile WebKit browser, we need to do some dreaded user agent sniffing:

1
2
var ua = navigator.userAgent,
  isMobileWebkit = /WebKit/.test(ua) && /Mobile/.test(ua);

In order to style the mobile version differently, we can now use our isMobileWebkit flag to add a class to our HTML element:

1
2
3
if (isMobileWebkit) {
  $('html').addClass('mobile');
}

Finally, we need to initalise iScroll if we’re on mobile:

1
2
3
4
var iScrollInstance;
if (isMobileWebkit) {
  iScrollInstance = new iScroll('scroller');
}

Now we can initalise Stellar.js differently whether we’re on desktop or mobile.

Understanding Stellar.js on mobile

Before we continue, it’s important to try to understand how Stellar.js is able to work with a touch scrolling library like iScroll.

Stellar.js has the concept of scroll properties which are adapters that tell it how to read the scroll position. The default scroll property is, appropriately enough, “scroll”, which covers the standard onscroll style animation.

When using Stellar.js’ default settings, it’s equivalent to writing this code:

1
2
3
$(window).stellar({
  scrollProperty: 'scroll'
});

Here you can see that we’ve specified that “window” is the source of our scrolling, and we read its scroll position using the “scroll” scroll property adapter.

Once we use iScroll, there is no longer a scroll position in the traditional sense. Native scroll is being simulated by moving the “scroller” div inside the “wrapper” div using CSS3 transforms.

Thankfully, Stellar.js has a “transform” adapter to cover this exact case. All we have to do is point Stellar.js at the div being moved, and specify which “scrollProperty” to use:

1
2
3
$('#scroller').stellar({
  scrollProperty: 'transform'
});

Performant positioning in Mobile WebKit

Repositioning elements rapidly is fairly demanding on mobile devices. In order to achieve a seamless effect, we need to ensure that our parallax effects are hardware accelerated.

In WebKit, hardware acceleration is triggered by using “translate3d”. Stellar.js provides support for this method of positioning via the “transform” position property adapter:

1
2
3
4
$('#scroller').stellar({
  scrollProperty: 'transform',
  positionProperty: 'transform'
});

By using this adapter, our parallax effects should now be as smooth as possible.

Hooking Stellar.js up to iScroll

Now that we’ve seen all the individual pieces needed to make our JavaScript work, it’s time to see the final script.js in its entirety:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(function(){
  var ua = navigator.userAgent,
    isMobileWebkit = /WebKit/.test(ua) && /Mobile/.test(ua);

  if (isMobileWebkit) {
    $('html').addClass('mobile');
  }

  $(function(){
    var iScrollInstance;

    if (isMobileWebkit) {
      iScrollInstance = new iScroll('wrapper');

      $('#scroller').stellar({
        scrollProperty: 'transform',
        positionProperty: 'transform',
        horizontalScrolling: false,
        verticalOffset: 150
      });
    } else {
      $.stellar({
        horizontalScrolling: false,
        verticalOffset: 150
      });
    }
  });

})();

Of course, this won’t work until we’ve updated our style sheet.

Styling for mobile

Finally, we add our mobile-specific styles which act on the body tag and our new iScroll containers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.mobile body {
  overflow: hidden;
}

.mobile #wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
}

.mobile #scroller {
  height: 3000px;
}

Seeing the end result

If you take a look at the final page, you’ll see we now have a page with scrolling parallax which works on desktop and mobile.

From here we have a base to play with our parallax site, while ensuring it works correctly cross-platform. At this point, if you haven’t already, it’s a good idea to read through the Stellar.js documentation to get a better idea of the control you have over the effect.

Have you made a cross-platform parallax site with Stellar.js? Let me know on Twitter, or post a link in the comments.

Update (27 Jan 2013): This article now reflects changes made in Stellar.js v0.6

Test-Driven Node.js Development With Grunt

One of the great things about working in a Node.js environment is that it encourages you to break your work down into discrete modules. Separating your work into smaller files is a good first step, but publishing to npm is so simple that creating small modules for others to share is a great way to give back to the community.

When writing small modules that adhere to the Unix philosophy of small programs doing one thing well, writing in a test-driven manner is almost a no brainer. However, getting a new Node project up and running can be a tedious process, particularly if you’re new to Node.

Luckily, Ben Alman has created Grunt, a project which is fast becoming the build tool of choice for the JavaScript community.

Getting started with Grunt

Grunt is pitched as a replacement for the usual Make/Jake/Cake style of tool by encouraging the use and development of plugins.

A handful of plugins are officially maintained by the Grunt team, but it’s the Grunt-init task that is the most powerful for those just starting out with Grunt. You can use this task to create a new Gruntfile, or to generate scaffolding for jQuery, CommonJS and Node.js projects.

To get started (assuming you have Git and Node.js installed), first install Grunt:

1
npm install -g grunt-init grunt-cli

This will install the Grunt CLI tool and Grunt-init globally, exposing the ‘grunt’ and ‘grunt-init’ commands respectively.

To complete our setup, we need to install the Grunt-init Node template into our ’~/.grunt-init’ directory using Git:

1
$ git clone git@github.com:gruntjs/grunt-init-node.git ~/.grunt-init/node

Scaffolding our module

For our test-driving example, we’ll create a simple project called ‘Palindrode’ for detecting whether a string is a palindrome. Our project will expose a single function called ‘test’ which, similar to the ‘test’ method of the ‘RegExp’ prototype, returns a boolean value.

To begin, we’ll initialise a new Node project:

1
2
3
$ mkdir palindrode
$ cd palindrode
$ grunt-init node

At this point, Grunt-init will ask a series of questions, most of which have sensible defaults based on your system. Grunt-init even detects that our module is called ‘palindrode’ based on the current directory. Upon answering them, the scaffolding for our new project is created:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Writing .gitignore...OK
Writing .jshintrc...OK
Writing Gruntfile.js...OK
Writing README.md...OK
Writing lib/palindrode.js...OK
Writing test/palindrode_test.js...OK
Writing LICENSE-MIT...OK
Writing package.json...OK

Initialized from template "node".
You should now install project dependencies with npm install. After that, you
may execute project tasks with grunt. For more information about installing
and configuring Grunt, please see the Getting Started guide:

http://gruntjs.com/getting-started

Done, without errors.

As the instructions have just informed us, we need to install our Node dependencies:

1
$ npm install

The code for our module goes in the newly generated lib/palindrode.js, and the tests go in test/palindrode_test.js.

Just to get used to the testing workflow, we can test our sample code:

1
2
3
4
5
6
$ grunt nodeunit
Running "nodeunit:files" (nodeunit) task
Testing palindrode_test.js.OK
>> 1 assertions passed (4ms)

Done, without errors.

Currently there is only one test, and the placeholder code to make the test pass, so you should find this passes with no issues.

Going for a test drive

Our test file, test/palindrode_test.js, already contains a placeholder test, including a Nodeunit reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
'use strict';

var palindrode = require('../lib/palindrode.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['awesome'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'no args': function(test) {
    test.expect(1);
    // tests here
    test.equal(palindrode.awesome(), 'awesome', 'should be awesome.');
    test.done();
  },
};

Let’s strip this back to a couple of simple palindrome tests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use strict';

var palindrode = require('../lib/palindrode.js');

exports['test'] = {
  'correctly matches palindrome string': function(test) {
    test.expect(1);
    test.ok(palindrode.test('Was it a car or a cat I saw?'));
    test.done();
  },
  'correctly matches non-palindrome strings': function(test) {
    test.expect(1);
    test.equal(palindrode.test('This is not a palindrome'), false);
    test.done();
  }
};

If we run the tests now, you’ll find they fail:

1
2
3
4
5
6
$ grunt nodeunit
Running "nodeunit:files" (nodeunit) task
...
Warning: 4/4 assertions failed (13ms) Use --force to continue.

Aborted due to warnings.

To make our tests pass, we need to edit our lib/palindrode.js, which currently looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
 * palindrode
 * https://github.com/markdalgleish/palindrode
 *
 * Copyright (c) 2013 Mark Dalgleish
 * Licensed under the MIT license.
 */

'use strict';

exports.awesome = function() {
  return 'awesome';
};

We need to replace the placeholder awesome function with a test function which returns a boolean. The important thing to note is that our module must ignore spaces and punctuation in order to correctly match sentence palindromes.

Let’s write a function which does this:

1
2
3
4
exports.test = function(string) {
  string = string.match(/[a-z0-9]/gi).join('').toLowerCase();
  return string === string.split('').reverse().join('');
};

This is enough to pass our two tests:

1
2
3
4
5
6
$ grunt nodeunit
Running "nodeunit:files" (nodeunit) task
Testing palindrode_test.js..OK
>> 2 assertions passed (6ms)

Done, without errors.

Currently our function will return true when passed empty strings or strings containing only spaces/punctuation. It will also throw an error if we pass it anything other than a string (or, more precisely, anything that doesn’t have a match method).

Let’s write a few more tests to make sure that our function is a bit more resilient:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'returns false when passed blank strings': function(test) {
  test.expect(1);
  test.equal(palindrode.test(''), false);
  test.done();
},
'returns false when passed only punctuation/spaces': function(test) {
  test.expect(1);
  test.equal(palindrode.test(' ?., '), false);
  test.done();
},
'returns false when passed non-string values': function(test) {
  test.expect(2);
  test.equal(palindrode.test(1234), false, 'should not accept numbers');
  test.equal(palindrode.test(), false, 'should not accept undefined');
  test.done();
}

Of course, these new tests won’t pass:

1
2
3
4
$ grunt nodeunit
Running "nodeunit:files" (nodeunit) task
...
Warning: 6/8 assertions failed (30ms) Use --force to continue.

Let’s upgrade Palindrode’s test function to pass these new tests:

1
2
3
4
5
6
7
8
9
10
11
exports.test = function(string) {
  if (typeof string !== 'string') {
    return false;
  }
  var matches = string.match(/[a-z0-9]/gi);
  if (matches === null) {
    return false;
  }
  string = matches.join('').toLowerCase();
  return string.length > 0 && string === string.split('').reverse().join('');
};

Our new tests now pass with flying colours:

1
2
3
4
5
6
$ grunt nodeunit
Running "nodeunit:files" (nodeunit) task
Testing palindrode_test.js.....OK
>> 6 assertions passed (6ms)

Done, without errors.

In the spirit of red/green/refactor, our final step is to clean up our code. We’ll move variable declarations to the top of the scope, use more descriptive variable names and separate the more complicated logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
exports.test = function(string) {
  var relevantCharacters,
      filteredString,
      reversedString;

  if (typeof string !== 'string') {
    return false;
  }

  relevantCharacters = string.match(/[a-z0-9]/gi);

  if (!relevantCharacters) {
    return false;
  }

  filteredString = relevantCharacters.join('').toLowerCase();
  reversedString = filteredString.split('').reverse().join('');

  return filteredString.length > 0 && filteredString === reversedString;
};

With Grunt’s help, writing a lightweight, tested module is incredibly easy.

It’s just as easy to include more tasks in our build to improve the quality of our module. For example, we can run our code through JSHint with the built-in jshint task. By default, if a Gruntfile exists in the current directory, running grunt with no parameters runs the jshint and nodeunit tasks.

If we wanted, the code is also ready to be published to npm using the npm publish command.

Testing continuously

We now have some tests and the code to make it pass. Thanks to Grunt, we also have a package.json file which specifies all our dependencies, and indicates that the npm test script should run grunt nodeunit.

All of this allows us to take advantage of Travis CI, a web-based continuous integration service.

There’s a few things we need to do to make this happen.

First, our code needs to be hosted on GitHub.

Next we create a file called .travis.yml, and specify that this is a Node.js project:

1
2
3
4
language: node_js

node_js:
  - 0.8

The final step is to log in to Travis CI using our GitHub account. On your Travis profile page you will see a list of public repositories, each with a switch to activate GitHub’s service hook.

Once activated, any time you push module updates to GitHub, the npm test script, which in turn calls onto grunt nodeunit, will be run in the cloud. If the build fails, we get notified via email.

Moving forward

With all of this in place, we now have a solid, tested module. Maintaining the quality of your module is simple, and thanks to GitHub’s new Commit Status API, Travis CI can now run your test suite against all pull requests.

To see a simple example of this setup in one of my own projects, check out lanyrd-scraper, a Node module for loading event data from Lanyrd.com.

Update (19 Feb 2013): This article now reflects changes made in Grunt v0.4