At the Forge

Introducing CoffeeScript

Reuven M. Lerner

Issue #208, August 2011

An attractive, new language that makes JavaScript programming fun and easy.

For many years, JavaScript had a bad reputation among developers. Sure, we would use it when we needed to do something dynamic in the browser, but we also would avoid it as much as possible. As I (and others) have written numerous times in the past year, however, JavaScript is going through a multidimensional renaissance. It executes quickly, and it increasingly is standardized and stable across browsers and implementations. You can use it in the traditional role of browser-side applications, either by itself or using a framework, such as jQuery. You even can build entire MVC applications in the browser using systems like Backbone.js, as I described in this space the past two months. And on the server, you can use node.js to create high-performance applications.

It's great that JavaScript has improved in many ways. At the same time, the language contains many legacy issues—not in terms of capabilities, but in terms of the syntax and grammar. You can do great things with JavaScript, but it's easy to write code that has unexpected side effects, whose variables don't have the scope you expect, or whose functions operate just differently enough from your intention to cause problems.

(Another thing that hasn't improved is its name and the fact that although everyone calls it “JavaScript”, it's officially known as “ECMAScript”, named for the standards body that approved it.)

One of the more interesting solutions to this problem has been the introduction of languages that are supersets of JavaScript. One of the best-known examples is Objective-J, which bolts an Objective-C-like syntax, object structure and class library onto JavaScript. The Cappuccino framework for in-browser MVC applications is written in Objective-J and provides a programming experience similar to that of the Cocoa platform for the Macintosh. Another solution has been to run a preprocessor on JavaScript code, as in the case of Google Closure. Closure compiles JavaScript into JavaScript, but in so doing, optimizes and minimizes your JavaScript code.

Another approach, taken by Jeremy Ashkenas (who, incidentally, also created the Backbone.js framework) was to create an entirely new language that compiles into JavaScript. This language, which he called CoffeeScript, is not designed to be run directly (although you can do so, with the right tools). Rather, CoffeeScript code is compiled into JavaScript code, which then is executed.

Why would you want to compile a program into JavaScript? First, because modern JavaScript engines are quite speedy. Compiling to JavaScript ensures that the execution will be fast, and that it will work on a wide variety of platforms and in many contexts—similar in many ways to the growing number of languages (for example, Clojure and Scala) that compile to JVM bytecodes. Second, if you can compile into JavaScript, you can take advantage of the libraries and frameworks that already work with JavaScript.

The other reason to use a language other than JavaScript, but that compiles into JavaScript, is that you can use a syntax that's more accessible and less prone to errors. I'm a longtime user of both Ruby and Python, and I found that CoffeeScript incorporated many of my favorite features from both languages to create a language with easy-to-understand syntax and powerful features. If you know Ruby, Python and JavaScript, you'll likely be able to learn this language in a relatively short time period.

Now, it's true that CoffeeScript has been around for about 18 months at the time of this writing, and that it already has attracted a number of fans. But, several events have made it even more interesting during the past few months. First, Brendan Eich, Mozilla's CTO and the inventor of JavaScript, said earlier this year that CoffeeScript may well provide some useful syntax ideas for the next version of JavaScript, known as “Harmony”. Douglas Crockford, well known for his ideas, writing and lectures about JavaScript, apparently has lent his support to CoffeeScript as well.

Even more significant, from my perspective, is that the Ruby on Rails core team has announced that CoffeeScript will be a standard part of Rails, starting with version 3.1. (Version 3.1 also will feature jQuery as the standard framework, replacing Prototype, and the incorporation of SASS, a CSS macros language.) I'm not going to explore the details of CoffeeScript and Rails here, but the fact that a large, growing, active and influential Web framework is adopting CoffeeScript will give JavaScript language architects like Eich a chance to see how it works “in the wild” and gather feedback from developers before deciding what will (and won't) go into the next version of JavaScript.

So, this month, I want to introduce some of the basics of CoffeeScript. I must admit I was skeptical of learning yet another new language, especially one that compiles into JavaScript. But after a bit of playing and experimentation, I see why people are so excited about it. Just where CoffeeScript will be in another few years remains to be seen, but it's certainly a useful tool to have right now, particularly if you're working on Web applications whose code has become increasingly twisted and complex with JavaScript functions.

Installing and Running

You can download and install CoffeeScript in a number of ways. One method is to download and compile the source from the GitHub account on which it is stored and developed. Just say:

git clone http://jashkenas.github.com/coffee-script/

and you will have the source on your machine. The CoffeeScript compiler depends on node.js, so it's not surprising that you also can download and install it using the node.js package manager, npm:

npm install coffee-script

Finally, some Linux packages (of various flavors) exist for CoffeeScript, for those who would prefer to install it alongside other packages, with dependencies taken care of.

Once you've installed it, you can involve the interactive command-line prompt, and start coding at the coffee> prompt.

You can print something immediately, using the built-in console.log function:

coffee> console.log "Hello, world"

What's console.log? It's a built-in function on the “console” object—for example:

coffee> console.log.toString()
console.log.toString()
function () {
  process.stdout.write(format.apply(this, arguments) + '\n');
}

As you can see, this lets you take a look at the JavaScript behind the scenes. If you do the same thing with the “console” object, you see something that looks even more like the JavaScript you know and love (or not):

coffee> console.toString()
console.toString()
[object Object]

In some ways, I haven't yet done anything different from standard JavaScript. JavaScript, after all, is all about functions—those that you can pass as parameters, and those that you can execute with parentheses, much like in Python. You can start to see the differences as soon as you define a function though:

coffee> hello_world = (name) -> console.log "Hello there, #{name}!"

First and foremost, you can see that defining a function in CoffeeScript is really a variable assignment. The function-definition syntax is still a bit weird by my standards, using -> to separate the parameters and body of an anonymous function. Parameters are named in parentheses, with commas separating them if necessary.

In this particular function body, I'm also using Ruby-style string interpolation to print the user's name. If you're tired of using + or a third-party library just to interpolate string values, this is likely to be a useful feature for you.

Basic Syntax

To execute the function, just give the CoffeeScript REPL (read-eval-print loop) the name of the function, followed by parentheses (that is, execution):

coffee> hello_world()

CoffeeScript functions return their final value, much as Ruby methods do. In the case of this hello_world function, that means the function is returning “undefined”. You can make that a bit better by having the function return the string, rather than print it:

coffee> hello_world = (name) -> "Hello there, #{name}!"

Then, you can say:

coffee> console.log hello_world('Reuven')
Hello there, Reuven!

or:

coffee> hello_world('Reuven')
'Hello there, Reuven!'

depending on whether you want to get the string back or just print it to the console.

CoffeeScript provides the basic JavaScript data types, but it adds a great deal of syntactic sugar, as well as additional methods, that make those data types easier to deal with. For example, CoffeeScript uses Python-style triple-quoted strings.

The “existential” operator, a question mark (?), allows you to determine whether a variable contains something other than null or undefined values. This is better than just checking for the truth of a value, which will lead to (literal!) false negatives if a value contains 0 or the empty string. For example:

v = 0

if v
    console.log "yes"
else
    console.log "no"

if v?
    console.log "yes"
else
    console.log "no"

The above code example shows how CoffeeScript implements if/else control blocks. There also is an “unless” operator, which (as you might expect) inverts the output from if. CoffeeScript also provides postfix “if” and “unless” statements—something you might recognize from Perl and Ruby.

You also can see another element of CoffeeScript above, this one taken from Python. Whitespace and indentation are significant, and allow you to remove much of the curly braces and begin/end of many other languages. Unlike Python, however, colons aren't necessary after the “if” and “else” statements.

CoffeeScript arrays are like JavaScript arrays, but with all sorts of nice syntax added. Want a ten-element array? Just use this:

a = [0..9]

and you'll get it, using the built-in “range” operator. (This doesn't work for letters though.) You can retrieve ranges as well:

a[5..7]

You can assign to a range, without worrying about the precise length of what you're splicing in:

a[5..7] = ['a', 'b']

You also can retrieve substrings using this syntax:

coffee> alphabet[5..10]
alphabet[5..10]
'fghijk'

CoffeeScript strings, like JavaScript strings, are immutable. Thus, you cannot assign to a substring:

coffee> alphabet[5..10] = [5]
alphabet[5..10] = [5]
[ 5 ]

coffee> alphabet
alphabet
'abcdefghijklmnopqrstuvwxyz'

JavaScript objects, which can be used like hashes (aka “dictionaries” or “associative arrays”) work just as they do in JavaScript, but with some easier syntax. For example, in JavaScript, you would write:

person = {
first_name: 'Reuven',
last_name: 'Lerner'
}

In CoffeeScript, you can say:

person =
    first_name: 'Reuven'
    last_name: 'Lerner'

Once again, using Python-style indentation instead of curly braces makes it more compact but no less readable.

Loops and Comprehensions

You can loop through arrays with for..in:

for number in a
    console.log number

I should point out that this will print each number on a line by itself and will return an array of undefined values (because console.log doesn't return a value, and “for” returns an array).

Objects can be accessed using the similar for..of loop:

for key, value of person
  console.log "key = '#{value}'"

Note that for..of loops work on any JavaScript object. Because every object can contain properties, and because arrays are objects, you even can assign properties to arrays:

a.foo = 'bar'

Using a for..in loop, you'll continue to see the values in the “a” array. But using a for..of loop, you'll get not only the array elements (whose keys are the indexes), but also “foo”. Additionally, note that if you're interested only in the properties defined on an object, rather than on its prototype, you can add the “own” keyword:

for own key, value of person
  console.log "key = '#{value}'"

In this particular case, there will be no difference. But if “person” were to have a prototype, and if the prototype were to have keys of its own, you would see the prototype's keys and values, and not just those for the “person” object.

But the need for these for..in and for..of loops is reduced dramatically in CoffeeScript because of comprehensions, an idea that comes from Python that takes some getting used to, but that offers a great deal of power and simplicity once you do so, allowing you to combine map, reduce and filter in a single statement. For example, you can take a list of numbers:

coffee> a = [100..110]
[ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 ]

And you then can multiply each number by 5, much as you would do with “map” in Ruby or Python, but using “comprehension” syntax:

coffee> i*5 for i in a
[ 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 550 ]

You also can select out some values. Suppose, for example, you want to operate only on those elements that are odd. You can say:

coffee> i*5 for i in a when i%2
[ 505, 515, 525, 535, 545 ]

Objects

As I wrote above, everything in JavaScript (and, thus, in CoffeeScript) is an object, and every object has properties. (Another way to think about this is to say that everything in JavaScript is a hash, with key-value pairs.) Understanding and working with this can be a bit confusing at first, particularly because of the way the “this” keyword operates. CoffeeScript offers several solutions to this problem, as well as the scoping and variable issues that drive JavaScript programmers crazy.

First, scoping of all variables is lexical and is obvious from the indentation. You can attach variables to the global object, or other objects, but you will end up doing this only when you want, not by mistakenly forgetting to add a “var” somewhere.

Second, properties can be accessed and assigned to as if they were variables, using Ruby-style @varname syntax. So, when you say x=5 in a CoffeeScript program, you're assigning the value 5 to the lexical value x. When you say @x=5 though, you're assigning the value 5 to the property x on the current object.

Finally, “this” is scoped dynamically in JavaScript, changing value to reflect the object to which the current function is attached. This means that if you aren't careful, you can write callback functions that reference “this”, but accidentally end up referring to the wrong object. CoffeeScript lets you define functions not only with -> (the “thin arrow”), but also with => (the “fat arrow”). The difference is that when you define functions with =>, they are bound to the value of “this” when it was defined, allowing access to the defining context's properties using @propname syntax.

All of these things come together in CoffeeScript's object model, which extends JavaScript's such that you can work with something resembling a traditional class-instance model, rather than the built-in, JavaScript-style prototype-based model. Prototypes still exist and work—and indeed, CoffeeScript's classes compile into JavaScript prototypes. But, you can get beyond prototype-style inheritance by declaring classes with a constructor. Here is a simple example of the sort of thing you can do:

class Person
    constructor: (firstName='NoFirst', lastName='NoLast') ->
        @firstName = firstName
        @lastName = lastName
        Person.count++

    @count: 0

p1 = new Person()
console.log p1
console.log Person.count

p2 = new Person('Reuven')
console.log p2
console.log Person.count

p3 = new Person('Reuven', 'Lerner')
console.log p3
console.log Person.count

When you run the above file, you get the following output:

{ firstName: 'NoFirst', lastName: 'NoLast' }
1
{ firstName: 'Reuven', lastName: 'NoLast' }
2
{ firstName: 'Reuven', lastName: 'Lerner' }
3

This not only shows how you can use CoffeeScript classes in a way similar to traditional classes, but also that you can have default values for function parameters by declaring their values before the -> sign. You also can see how naturally the use of the @propname syntax fits into this object model. The above constructor looks almost like a Ruby method, rather than a JavaScript one, with a clear distinction between local variables and instance variables.

Conclusion

CoffeeScript is an attractive, new language that makes JavaScript programming fun and easy. You can think of it as JavaScript with a new syntax or as an easy-to-learn language that integrates into JavaScript applications, with many ideas taken from Python and Ruby. It removes many of the syntactic bloat and issues associated with traditional JavaScript, simultaneously providing a language that's easier to write and maintain, but also faster to execute, than raw, unoptimized JavaScript. CoffeeScript is a language we all should watch in the coming months and years. It probably won't replace JavaScript altogether, but it definitely will make it easier to accomplish certain tasks.

Next month, I'll look at how CoffeeScript can be integrated into your browser-side Web applications, especially those using jQuery. That's the direction the Ruby on Rails community seems to be moving toward with its 3.1 release, and even if your favorite framework doesn't adopt CoffeeScript, understanding how they work together probably will be useful.

Reuven M. Lerner is a longtime Web developer, architect and trainer. He is a PhD candidate in learning sciences at Northwestern University, researching the design and analysis of collaborative on-line communities. Reuven lives with his wife and three children in Modi'in, Israel.