Ryan Jacobs


Getting Started with CoffeeScript

What is CoffeeScript?

Description straight from coffeescript.org,

"CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable and pretty-printed, will work in every JavaScript runtime, and tends to run as fast or faster than the equivalent handwritten JavaScript."

Installing CoffeeScript

For the sake of this guide I am going to assume you are running a Debian or Ubuntu based operation system. If you're running anything else, you probably know what you're doing anyways.

$ sudo apt-get install nodejs nodejs-dev npm
$ sudo npm install -g coffee-script

Compiling CoffeeScript Code

Yay! Now we have the CoffeeScript compiler installed! Let's create some simple code and run it.

  1. Create the file 'HelloWorld.coffee'.
  2. Paste this code into 'HelloWorld.coffee' and save it.
# Yet Another CoffeeScript HelloWorld
# By the way, '#' is a comment in CoffeeScript
# Also, 'console.log' prints text

## Define some functions ##
square = (x) -> x * x
cube   = (x) -> square(x) * x

printSquare = (x) ->
    mySquare = square(x)
    console.log "The square of", x, "is", mySquare

## Loop example ##
for num in [1..5]
    printSquare(num)

console.log "" # sends a newline
cubeMe = [ 123, 124, 125, 122, 121, 120 ]
cubes  = (cube x for x in cubeMe)

# Print first 5 cubes
for c in [0..4]
    console.log cubeMe[c] + "^3 ->", cubes[c]

console.log ""
console.log "Oh yeah, I forgot..."
console.log "HELLO WORLD!"

Running It

Simply run the file with:

$ coffee HelloWorld.coffee

To compile the CoffeeScript files into a JavaScript file:

$ coffee -c HelloWorld.coffee

Yay!

Yay, we did it! We compiled some CoffeeScript code and ran it! Well, that's the gist of it. To learn more about CoffeeScript, checkout the links below.

Further Reading

If you are going to be using CoffeeScript in the near future, coffeescript.org is a must read. It walkthroughs every cool feature of CoffeeScript and and its JavaScript equivalent.

If you want to learn CoffeeScript extensively, read this little e-book called The Little Book of CoffeeScript.