Introducing CoffeeScript

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.

______________________

Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer,
is completing his PhD in learning sciences at Northwestern University.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Javascript is still alive

Anonymous's picture

Just goes to show that Javascript is still alive.I wonder how much memory it takes to compile from Coffee Script into Javascript.That might be a limiting factor in development.

The setup was confusing. How

Sannomo's picture

The setup was confusing. How would you set this up for testing in a web browser?

Quite bad code formatting for

Anonymous's picture

Quite bad code formatting for a whitespace-aware language.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix