CoffeeScript is a lightweight language based on Ruby and Python that compiles into JavaScript. It was the brain child of Jeremy Ashkenas, a lead developer for an open source tool for journalists called DocumentCloud. His aim was to make writing JavaScript code easier by providing a more consistent and succinct syntax, while avoiding the quirky and/or irregular “features” of the JavaScript language. Proponents say it’s fun, and even addictive sometimes! Others, are not so sure of it’s ultimate usefulness. At the end of the day, the key question is whether or not CoffeeScript really is easier than writing pure JavaScript. We’re going see if we can answer that question today.
Getting Up and Running
CoffeeScript is an open source project and resides on GitHub. The command-line version is available as a Node.js utility, which is a platform built on Chrome’s JavaScript runtime for building scalable network applications. It comes as a Windows or Mac installer as well as a compressed source code file (in tar/gzip format). Which ever you choose, the files are quite small. For instance, the Windows installer is only 3.41 MBs.
To install CoffeeScript, download the latest stable version of Node.js. It includes the Node Package Manager (npm). You can then install CoffeeScript using the following npm command:
npm install -g coffee-script
The -g flag can be omitted if you don’t wish to install globally.
Another option is to clone the CoffeeScript source repository from GitHub, or download the source directly. You can then install the CoffeeScript compiler system-wide under /usr/local by navigating to that directory and issuing the command:
sudo bin/cake install
Skipping the Compile Step
It might seem counterproductive to go through the trouble of installing the compiler only to ignore it, but it can make sense to develop without compiling every change that you make. Just don’t try it in production, unless you want scripts that run twice as slowly! The CoffeeScript-to-JavaScript translator is actually the coffee-script.js script. It can be run in any JavaScript-capable environment, such as a browser. All you need for that to work is to include the latest coffee-script.js file in your HTML source:
<h1>My First CoffeeScript Page</h1> <script src="coffee-script.js" type="text/javascript" charset="utf-8"></script> <script type="text/coffeescript"> # Some CoffeeScript wordList = ["coffeescript", "Jeremy Ashkenas", "DocumentCloud", "and stuff", "jQuery"] tweet = "This is an example tweet talking about javascript and stuff." console.log wordList.some (word) -> ~tweet.indexOf word #outputs true </script>
Compiling your Scripts
There are other compilers available out there besides the one which comes with CoffeeScript. I heard good things about Alisey’s CoffeeScript-Compiler-for-Windows, so I decided to give it a try. The compilation process is exactly the same using it as the native complier. To install it, I did the following:
- Downloaded Node.js executable for Windows.
- Downloaded CoffeeScript.
- Copied the coffee.exe program into my CoffeeScript scripts directory (under lib\coffee-script).
- I found that the coffee-script.js file that came with the CoffeeScript installation did not work properly so I had to download the latest one from the master CoffeeScript Github directory.
- Added the CoffeeScript scripts directory (under lib\coffee-script) to my path environment variable.
Let’s compile a really simple script. Here’s some code that will print “Odelay!” five times:
print "Odelay!" for i in [1..5]
Notice how there are very few extra characters like parentheses or curly braces. You can see why people describe CoffeeScript as being a succinct language!
Although you could say that the coffee.exe technically does complile the code, it seems to resemble a transformation to me, but that’s neither here nor there. To compile the script, save it with a .coffee extension, as in something like “compileTest.coffee”. Then navigate to the folder that contains your script file. In windows, I started the DOS command prompt and used the “cd” command. Then run the coffee executable with the –compile or -c flag, followed by the name of the file:
E:\>cd E:\CoffeeScript\article>coffee E:\CoffeeScript\article>coffee -c compileTest.coffee
A couple of other useful flags include:
- -o, –output [DIR]: Sets the directory for the compiled JavaScript file. Useful for changing the name as well as the location.
- -j, –join [FILE]: Concatenates two scripts before compiling.
Open the new JS file and you should see something like the following:
(function() { var i, _i; for (i = _i = 1; _i <= 5; i = ++_i) { print("Odelay!"); } }).call(this);
You can now use the .js file just as you would any JavaScript file.
Automating the Compilation Process
One of the main criticisms of CoffeeScript is that it puts another layer between you and JavaScript, namely the compiler. Having to manually compile CoffeeScript files whenever they change is a bit of a pain. The cake library is bundled with the coffee-script npm package, and available via an executable called cake.exe. You can define tasks using CoffeeScript in a file called Cakefile. Cake will pick these up, and can be invoked by running “cake [task] [options]” from within the directory. Tasks are defined using the task() function, passing a name, optional description and callback function. Here’s an example that watches the src folder for changes and compiles source files whenever they are modified:
task('watch', 'Watch src/ for changes', function() { var coffee; return coffee = spawn('coffee', ['-w', '-c', '-o', 'lib', 'src'](coffee.stderr.on('data', function(data) { return process.stderr.write(data.toString()(coffee.stdout.on('data', function(data) { return print(data.toString()); }))); }))); });
Final Thoughts
The main argument for using CoffeeScript is that it’s more readable and should therefore be easier to write, debug and maintain. However, reading something and comprehending something are very different. Another issue I have is with the abstraction of JS libraries such as jQuery. Since jQuery is itself a sort of abstraction of JavaScript, then coding in CoffeeScript for jQuery becomes an abstraction of an abstraction; at that point the level of syntax shortening becomes more bastardization than shortcut. It would also seem to me that any time saved on typing is then lost on debugging since you have to match up the compiled javascript which you are debugging against the CoffeeScript source which you are changing. In closing, I would suggest that you consider CoffeeScript as an alternative to pure JS coding only if you’ve ascertained beyond a reasonable doubt that the language gives you grief and that popular JS libraries aren’t helping any. Then again, if JavaScript if giving you such a hard time, I might also recommend that you consider an easier job, such as musician!*
*To all my musician friends: Just kidding. 🙂 You work hard, I know!