CoffeeScript Beginner Beginner’s Guide

 Introduction

Hey there! You’ve found my intro to CoffeeScript page. You can learn CoffeeScript at the same time I do! I’m no expert, but I’ve learned a few things and thought it would be good to share. This is my beginner beginner’s guide.

CoffeeScript is a self-described “little language” that compiles to Javascript.  I’ve also seen it described as a Javascript pattern-handler, in that it takes common Javascript patterns and gives the developer easier and shorter programming alternatives to write the pattern. For example, and I will get into this is more detail later, CoffeeScript allows you to use classes in a similar way to Ruby or Python, while actually using prototypal syntax behind the scenes. This saves the developer a lot of writing, as we will see.

This tutorial will include written explanations and demo videos. They will be divided into sections based on themes in CoffeeScript. This was my first time uploading videos and I couldn’t figure out how to edit them without majorly decreasing quality, so unfortunately to strike a balance they’re a bit blurry. Any helpful hints would be appreciated!

Getting Started

There are a couple ways to get CoffeeScript working on your machine.

Online Testing

CoffeeScript’s website, http://coffeescript.org, has a browser-based testing tool. It’s handy to try out your script, but it does not have a console viewing option. You can see what your CoffeeScript compiles to, but it doesn’t allow you to see what you’re actually going to output onto the browser window (or whatever platform you’re using).

Download via Command Line or Compressed File

Instructions to do this are viewable on CoffeeScript’s website. To install via the command line you will need to have previously installed Node.js.

My Recommended Extras

I found it extremely handy to tell my computer to automatically compile my CoffeeScript files and output them into separate Javascript files. This can be done by setting up separate folders and then running this command:

coffee -w -o javascripts/ -c coffeescripts/

Complete instructions can be found in this guide.

I prefer using Sublime Text 2 as my text editor, and there is a CoffeeScript syntax highlighter that can be added via Package Control.
I have also added a Javascript Build option so that I can see the results of all of my console.log’s.

Or, if you prefer, there is a TextMate plug-in designed by the makers of CoffeeScript that you can use.

Now you should be ready to follow along with me! And if you didn’t get it quite working, don’t worry — I’ve included videos so you can follow along with what I’m typing and see the output.

Comments

Comments in CoffeeScript are a bit different — instead of using the // or /* */ syntax you might be used to in Javascript, CoffeeScript uses hash signs #.

// Single line comment

becomes

# Single line comment

and

/* Multi line comment*/

becomes

### Multi line comment ###

Only multiline comments are compiled and shown in outputted Javascript, as shown in the video:

Variables, Arrays, and Objects

Variables

In CoffeeScript, there is no need to write var before your variables. CoffeeScript implicitly includes the var with every variable for you.

var myVariable = "Javascript syntax for assigning a variable.";

becomes

myVariable = "CoffeeScript syntax for assigning a variable."

This is helpful if you’ve ever found yourself forgetting to type var before assigning a variable in a function and accidentally creating a global variable (or overwriting an existing one).

You can still set a global variable within a function if needed by assigning the variable to the window, i.e.

#CoffeeScript
window.myVariable = "I am a global variable."

Arrays

Writing arrays in CoffeeScript is very similar to writing them in Javascript. You will still need to include square brackets around your array. You may then input your values on one line separated by commas:

#CoffeeScript
array = [1, 2, 3, 4, 5]

Or, you can input your values on separate lines or “matrix” style, keeping whitespace rules in mind:

#CoffeeScript
array = [
   1, 2, 3
   4, 5, 6
]

Notice on this second option you do not need commas at the end of each line of items on your array, the line break and whitespace will tell CoffeeScript how to parse the items.

Objects

Objects are also written similarly to the way they’re formatted in Javascript, but unlike with arrays we do not use any brackets. The use of curly brackets in Object syntax is entirely replaced by whitespace usage.

#CoffeeScript
myObject = 
   numbersLetters:
      one: "a"
      "two": "b"
      three: 3
   namesAges:
      sally: 3
      jack: 7

Functions

The way to write functions in CoffeeScript has been simplified from the way it is written in Javascript.

//Javascript
myFunction = function() {
     return 1;
}

In CoffeeScript, the function directly preceding the parameter inclusion is removed entirely, and the curly brackets are replaced by an arrow operator:

#CoffeeScript
myFunction = -> 1

If there are no parameters to include, the arrow operator can follow immediately after the equals sign. Since this simple function is only one line, it can all be written as one line.

You may have noticed that the CoffeeScript function also doesn’t include a return. It actually does, but CoffeeScript again takes care of that for you by automatically applying a return to the last line of every function. This is something to keep in mind when you’re writing your code.

For more complex functions that might include parameters or are multiline, the format is as follows:

#CoffeeScript
myComplexFunction = (a, b) ->
     a = b*b
     4*a

This would return the computation of 4*a.

CoffeeScript also includes a handy way to include default parameters:

#CoffeeScript
parameterExample = (a=1, b=2) -> a*b

All you need to do to tell CoffeeScript to check for null (and assign the value to the parameter if the value is null) is include a value after an equals sign within your parameter declaration. This means that if you include values for and when calling the function, it will overwrite the defaults and use your specified values. However, if you call the function without specifying parameters, the function will use the default values (and the above example would evaluate to 2).

CoffeeScript has also made calling functions simpler (or more confusing, depending on your background) by having any value immediately following the function name and a space be treated as a parameter for the called function. If you don’t have any parameters you must still use the brackets:

parameterExample()        
#Using the above function, evaluates to 2

But when using parameters they may simply be included after a space:

parameterExample 2,4      
#Using the above function, evaluates to 8

A few other helpful hints

Instance Variables

In Javascript, you may be used to using this to refer to the instance variable. CoffeeScript uses an alias of @ for efficiency (although, since CoffeeScript compiles to Javascript, using this would still work).

//Javascript
this.name

becomes

#CoffeeScript
@name

If/Else statements

Like functions, if/else statements also lose their brackets and rely on whitespace for parsing instructions:

#CoffeeScript
if car.isOn
   console.log "Go!"
else 
   console.log "Don't go!"

Operators

In CoffeeScript, operators have been modified to make them more intuitive and similar to the way you would speak english. So instead of using &&, you could just use the now-operator and. Similarly, true can now be expressed by using trueyes, or on.

COFFEESCRIPT JAVASCRIPT
is ===
isnt !==
not !
and &&
or ||
true, yes, on true
false, no, off false
@, this this
of in
in no JS equivalent

Handy operator chart via the treehouse blog.

CoffeeScript also allows you to use if or unless in postfix, allowing you to code fun things like this:

#CoffeeScript
dinner = if bolognese is true then "spaghetti" else "linguini"

Classes

One of the most useful parts of CoffeeScript (or a way to “cheat” Javascript, according to some) is its included class functionality. In the background, the prototype model is still being used, but CoffeeScript packages it in such a way that using classes is similar to how they would be used in OOP languages like Python or Ruby. Creating a class follows this syntax (and, typically for me, includes a whale):

class Whale
 constructor: (@name) ->

 type: (eatingApparatus) ->
 console.log "The "+ @name + " has some " + eatingApparatus

You now have a Whale class to use in your code. Notice how we used the @ syntax for our constructor variable? This means you can just include the name on the same line when creating a new Whale class. You can also extend classes and use the super method comparatively easily:

class Odontocete extends Whale
 type: ->
 super "Teeth"

class Mysticete extends Whale
 type: ->
 super "Baleen"

orca = new Odontocete "Orca"
right = new Mysticete "Right Whale"

In case anyone is curious, Odontocetes are toothed whales, and Mysticetes are baleen whales. You’re welcome.

Using the super method here still relies on Javascript’s prototypal inheritance behind the scenes to act on the class’s parent. So, calling orca‘s or right‘s type gives you a bit of interesting information:

orca.type()       # The Orca has some Teeth
right.type()      # The Right Whale has some Baleen

Discussion

There are many more fun things you can do with CoffeeScript that I will leave you to find out (like splats…!) and there are great resources out there to add to your knowledge. I used CoffeeScript’s website along with some other great introductory guides like The Little Book on CoffeeScript and the aforementioned treehouse blog.

For me, learning CoffeeScript has been pretty fun, and makes me want to learn some of the OOP languages its syntax “sugar” is based on, like Ruby or Python. But more immediately, I find myself using it to write complex Javascript for me (read: anything to do with the prototype model). Then I can continue on coding in raw Javascript, potential prototype crises averted. This is a kind of counterintuitive way to use CoffeeScript, but it works for me.

Another immediate pro of CoffeeScript is that it is 2/3 the size of the equivalent Javascript file (although if you’re using classes a lot I can see that fraction getting even smaller). The compiled Javascript is also formatted according to Douglas Crockford’s guidelines in “JavaScript: The Good Parts“, meaning it is easy to read and follows best practices.

I can also easily see CoffeeScript as an excuse not to learn its equivalencies in raw Javascript — I’m already dodging anything to do with prototypes.  This can lead to problems with debugging outputted Javascript if you don’t quite know what you’re looking at, having avoided learning its syntax in the first place.  CoffeeScript’s error output is also not as complete as Javascript’s, but it’s getting better and I found it relatively easy to interpret.

CoffeeScript’s automatic return at the end of all of its functions could also cause some grief if you forget that the functionality exists or if you don’t actually want your function to return anything for whatever reason.

CoffeeScript’s self-purported golden rule is “it’s just Javascript“, which apparently is code for we’re lazy, make our syntax easier. Or at least according to some other people on the internet who are seemingly angry about it. (I may be ignoring some other valid points they bring up, but the tone of many dissidents seems to be Ugh, just use Javascript you lazy creatures.) A few definitely make a valid point that CoffeeScript is not its own language but rather a handler for Javascript design patterns. Jeff Walker makes some valid points about how some of CoffeeScript’s changes can actually make writing it more confusing instead of more intuitive.

In any case, I would say that CoffeeScript can be a handy little learning tool, and in my case can be used to check that I’m using snippets of raw Javascript properly. I don’t think it’s necessarily useful to have whole files in CoffeeScript, but I also don’t see why doing so would be an enormous detriment if used correctly and if your dev team understands how it compiles. CoffeeScript should not stop you from learning raw Javascript (especially because Javascript is used much more broadly) but if it helps you out, go for it.

If you’ve read all the way through (thanks!) and want to try this out, I’ll include an example guide below that includes both a coffee file and a js file to show the differences between the CoffeeScript concepts we just learned and their Javascript equivalents. Happy learning!

CoffeeScript Example Guide

coffeeIntro

 

EDIT: Somehow I didn’t include this video in here anywhere, so here’s a bonus extra blurry video about loops. Yay!

Leave a Reply