Steve Fenton

CoffeeScript comparison

As I’m in the middle of writing a JavaScript unit testing framework, I thought the best way of trying out CoffeeScript would be to re-write an existing unit test class from JavaScript to CoffeeScript and then see what the compiled output looks like in comparison.

If you want to play along and haven’t set up CoffeeScript, read how to get started with CoffeeScript.

My Hand Cranked JavaScript

This is file I originally created by hand. We will compare the final output to this later on.

var SampleTest = (function () {
    return {
        addTwoNumbersWith2and3Expect5: function () {
            var result = Sample.addTwoNumbers(2, 3);
            Assert.areIdentical(5, result);
        addTwoNumbersWith3and3Expect6: function () {
            var result = Sample.addTwoNumbers(3, 3);
            Assert.areIdentical(6, result);


CoffeeScript Version

When you rewrite this in CoffeeScript, it actually looks quite nice.

class SampleTest
  this.addTwoNumbersWith2and3Expect5 = ->
    result = Sample.addTwoNumbers(2, 3)
    Assert.areIdentical(5, result)
  this.addTwoNumbersWith3and3Expect6 = ->
    result = Sample.addTwoNumbers(3, 3)
    Assert.areIdentical(6, result)


The Compiled Output

One command later, we have a JavaScript file that looks like this:

// Generated by CoffeeScript 1.3.1
(function() {
  var SampleTest;

  SampleTest = (function() { = 'SampleTest';

    function SampleTest() {}

    SampleTest.addTwoNumbersWith2and3Expect5 = function() {
      var result;
      result = Sample.addTwoNumbers(2, 3);
      return Assert.areIdentical(5, result);

    SampleTest.addTwoNumbersWith3and3Expect6 = function() {
      var result;
      result = Sample.addTwoNumbers(3, 3);
      return Assert.areIdentical(6, result);

    return SampleTest;


And that isn’t a million miles away from the original – but with the benefit of a (subjectively) tidier file to work with – it was 14 lines of JavaScript and 9 lines of CoffeeScript, with less chuff around the edges and with a clever compiler that knows what Douglas Crockford thinks we should be doing.

Written by Steve Fenton on