Writing Better JavaScript with CoffeeScript: The Basics

Nov 3 2011 by Jack Franklin | 17 Comments

I’m a huge fan of JavaScript. Its popularity has really surged in recent years with the advent of rich internet applications (RIAs), Ajax and web development libraries like jQuery that makes JavaScript more appealing and accessible to a broader audience.

However, that doesn’t mean the language is without its quirks, and often these can come from nowhere to bite you. There’s a long running joke about JavaScript’s good parts compared to its bad parts and how the language has many problems. In this multi-part guide, I’ll present you with a solution to most of these problems: CoffeeScript.

This is the first part a series of articles that introduces you to this wonderful programming language.

What is CoffeeScript?

CoffeeScript is a small programming language that compiles into JavaScript. It seeks to make writing JavaScript code better by providing you with a more consistent and succinct syntax, as well as by avoiding the "bad parts" and quirky/irregular nature of the JavaScript language.

CoffeeScript official siteThe official CoffeeScript website.

CoffeeScript was created by developer Jeremy Ashkenas, a lead developer for DocumentCloud (an open source tool for journalists).

Jeremy Ashkenas, creator of CoffeeScript. Source

CoffeeScript is an open source project. You can find the CoffeeScript source code on GitHub.

How CoffeeScript Works

The code writing and use process of CoffeeScript is simple:

  1. Write your code in a .coffee file
  2. Compile it into a .js file
  3. Include the .js file in your web page/s like you would any other JavaScript file

How CoffeeScript Works

If you’re someone who fears the word "compile" (in step 2 above) don’t worry – later on, we’ll look at some tools to make all the compiling automated.

CoffeeScript Code Example

Let’s jump right in by showing you a small snippet of JavaScript (using jQuery), and then the same code written in CoffeeScript.

The function will write Hey Six Revisions readers! inside the <body> tag of the web page.

JavaScript:

$(function() {
  $("body").html("Hey Six Revision readers!");
})

CoffeeScript:

$ ->
  $("body").html "Hey Six Revision readers!"

CoffeeScript allows you to write JavaScript quicker due to its slimmed-down, simplified syntax.

Here are two basic rules to remember:

  1. Whitespace matters. There are no curly braces (e.g. {[statements]}) in CoffeeScript. Instead, indentations are used.
  2. No parentheses. Functions that take arguments do not need parentheses (e.g. (argument)) around them as you can see in the code above. You can use them if you like, and in some places of your script, it might make your code more readable, but most of the time you can leave them out. Multiple arguments being passed in are separated with a comma (e.g. argument1, argument2, argumentN).

JavaScript Syntax vs. CoffeeScript Syntax

So, going back to our above code example, let’s look at some differences between JavaScript and CoffeeScript.

Firstly, you can see we’ve replaced function() {} simply with $ ->. The first line becomes $ ->, which calls jQuery and passes in an anonymous function.

If you wanted to declare a function that takes arguments, in JavaScript it would be like so:

function say(something) {
  alert(something);
}

But in CoffeeScript, it’s terser:

say = (something) ->
	alert something

You’ll also notice we can leave out semicolons (;). CoffeeScript adds them in when it compiles.

Another good thing is that you don’t need to use the var statement, which you should use when you’re writing in JavaScript to avoid accidentally creating global variables.

So instead of:

var a = 2;

We can just write:

a = 2

All of this may seem hard to get used to at first — especially if you are more familiar with programming languages like PHP that use curly braces ({}) to enclose a statement block and semicolons (;) to indicate the end of a statement — but it is much quicker to type, and over time, it becomes natural.

Installing CoffeeScript

By far, the most popular installation of CoffeeScript is to install the command-line version through Node.js.

First, make sure you’ve got Node.js and that the Node Package Manager installed.

Then, to install CofeeScript, issue the following command:

npm install -g coffee-script

Compiling CoffeeScript Files

To compile a CoffeeScript file, navigate to the directory it’s stored in and type this command in the terminal:

coffee --watch --compile example.coffee

That command will automatically recompile example.coffee into example.js every time you save the file because of the --watch option, which monitors modifications of the CoffeeScript file.

All the CoffeeScript command options can be found on the CoffeeScript documentation on GitHub.

For those on Windows without Node.js installed, I was able to locate an open source project called CoffeeScript compiler for Windows by Alexey Levedev. I cannot vouch for it because I haven’t tried it, but it might be worth a try. I do highly recommend installing with Node, however.

I also managed to find LiveReload 2, a Mac app that watches your folders for file changes and automatically refreshes the page. The key thing is that LiveReload can automatically compile CoffeeScript for you, thus avoiding any need to go via the terminal. Unfortunately, this is a Mac-only app. If you know of any similar programs for Windows, please share it in the comments.

Summary

This is the end of our first guide on CoffeeScript.

This is what we covered:

  • What CoffeeScript is
  • Advantages of CoffeeScript over JavaScript
  • How CoffeeScript works
  • The most important bits of CoffeeScript syntax
  • A comparison of CoffeeScript versus JavaScript syntax
  • How to install CoffeeScript
  • How to compile CoffeeScript into JavaScript

In part 2 (coming soon), we’ll dive further into the CoffeeScript syntax and cover everything in more detail.

Related Content

About the Author

Jack Franklin is a 19-year-old web developer and university student from Bath, UK. He has a passion for clean code and a huge interest in JavaScript, alongside HTML, CSS, PHP, Ruby and Objective-C. See his work and read his blog on his portfolio site and find him on Twitter: @Jack_Franklin.

17 Comments

Daniel15

November 3rd, 2011

Great introduction. I don’t think it’s a good idea to use jQuery in a CoffeeScript tutorial, as I’m assuming the next parts will be mostly CoffeeScript-specific. Keep it simple and use DOM methods or regular innerHTML :)

safetycopy

November 3rd, 2011

A nice little intro. Just as an FYI, VIm users can check out https://github.com/kchmck/vim-coffee-script. In your .vimrc add something like ‘autocmd! BufWritePost *.coffee silent CoffeeMake! -b’ and you’ll auto-compile the .coffee file whenever you save :-]

Imtiaj

November 3rd, 2011

JavaScript is a bit complicated when writing code, where CoffeeScripts can be written with less code with no effect on runtime performance.

Mustified

November 3rd, 2011

This is really interesting, but it will take some time to get into it and develop something with the help of coffeescript. Though the compiling part left a lot of questions in my mind.

Anyways… I will get back here after trying it. Thanks Jack for writing such a helpful article.

CoffeScript Hater

November 3rd, 2011

Boo… Javascript is fine on its on, adding an abstraction layer to an already elegant language is blasphemous. Boo!

Ramón Ramos

November 3rd, 2011

Hmmm…

It’s like the templating platform for PHP, you know, when PHP should suffice as templating platform.

Code maintenance and debugging must be a pain in the a$$, since you don’t know the code tuning happening behind your back.

I’m not really into platforms that compile into scripting files, that’s just wrong. But hey, i’ve been (almost) wrong before.

Henry Louis

November 4th, 2011

It is an interesting tutorial regarding JavaScript with coffee script. I hope it is more helpful to the people those who want to learn JavaScript.

Danilo de Castro

November 4th, 2011

I’ve agreed with CoffeScript Hater, javascript is good enough. It’s not necessary create a new language to build a code stronger.

GarcíaWebDev

November 4th, 2011

Hey Ramón, I’m not sure that code compiling is wrong. The apps you use every day are compiled to binary code for the computer to interpret. And there’s no “binary” programmer that says “compiling’s wrong, code in binary”. It would be a pain in the ass. That’s why compilers are there for. Also, check Compass Framework, it compiles SCSS to CSS and if you read the outputted code, it’s very nice. Output quality It’s in the quality of the compiler, not the compiling process per se.

coderbay

November 4th, 2011

good explanation of coffeScritp. thanks

Jack Franklin

November 6th, 2011

Hey Guys,

Thank you for the comments and I’m glad to hear that most of you enjoyed the article. For those not yet convinced, after we look more in-depth at what CoffeeScript has to offer in an upcoming post, I hope I can bring you round.

Thanks again,

Jack.

Bas

November 7th, 2011

I agree with the “CoffeeScript haters”. Javascript is a good language on it’s own. The abstraction layer just makes it more complicated. It also requires the developer to compile it, test it, debug it, compile it again, debug it again, etc… jQuery is a nice layer to JavaScript, CoffeeScript is just a typical way of a programmer creating a hard time for himself. Lot’s of programmers tend to do this. Still don’t know why.

Chris Orlando

November 7th, 2011

…I am going to use real languages to see if i get this concept. I write a novel in simplified english, press a button and i get oxford english? And if someone after me wants to read and edit does not know simplified english but can edit right away on the oxford english?

Mr.Ahmed Hussein

November 10th, 2011

Thank You, Jack Franklin :)

deadwin

November 14th, 2011

That’s really a nice way of using Javascript. I will definitely use this in my next project. As a beginner there should be some more tutorial so that we guys can easily learn it.

Peter Simmons

December 12th, 2011

Great intro nothing I see that makes me want to use coffeescript yet but I’ll keep reading.

FYI: Need to update the details for install and around windows now that node supports them both and also npm is bundled with node now as well. Node now comes with packages for Windows, Mac OS X, Linux for installing too so maybe just point at those to save future updated.

lol

October 8th, 2012

–sorry about by english–

just its syntax make me hate it.
holy shit, just think in the mess…. where is the parenteses? where is the brackets?

say = (something) -> ???
fuck off! i don’t understand it, i want a big fucking FUNCTION written on the middle of it, so i can understand it that is a FUNCTION

after all. that thing was create to make me angry and confused or it was supposed to help me?

Leave a Comment

Subscribe to the comments on this article.