Advertisement

Rocking Out With CoffeeScript

Read Time: 12 min

Even though CoffeeScript is a new language, you'll learn it very quickly. You should, since it's only JavaScript flaunting with some flashy clothes, after all. It reads like Ruby or Python, but compiles down to pure, non-fluffy JavaScript. Today, we're going to take a look at why everyone is talking about CoffeeScript.

A Word From the Author

With the advent of powerful JavaScript engines, like V8, JavaScript has shed its stigma of a gimped tool for juvenile interactions and morphed into quite a powerhouse. It has even jumped from client side applications to server side, node.js for instance. The fact that it adheres to a pretty nifty, prototype based ideology doesn't hurt it either. There is no doubt that JavaScript is indeed a critical language now and for the foreseeable future.

But I've always felt the syntax itself to be a bit kludgy. After working with a mix of Ruby and Python over the past couple of years, I've been finding JavaScript's semi-colon infused, parentheses dependent, verbose syntax to be tedious. And from what I can gather, I'm not alone in feeling this way. This is where CoffeeScript comes to the rescue!

What is CoffeeScript?

CoffeeScript compiles down to raw JS.

CoffeeScript is essentially just a syntactic rewrite of JavaScript. The core language itself stays the same, with small semantic enhancements. The syntax is modified, modeled after Python and Ruby.

Remember that the CoffeeScript compiler outputs clean JavaScript that not only follows best practices and is eminently readable but also passes JSLint. This means that you don't have to worry about compatibility down the line. In the worst case scenario of this project dying, you can just pick up the pristine JS that CoffeeScript generates and move on with your code. You aren't locked into this environment.

This may seem like an alien concept but under the web development umbrella, we've already seen our fair share of this ideology. HAML is but a new way of writing HTML while SASS does the same for CSS. All of them clean up the structure and syntax of their languages making them more easier to work with and thus boosting our productivity.

Some Quick Code

You're probably wondering how the code itself looks so here is a quick peek:

 1 2 index = (list, target) ->  3  [low, high] = [0, list.length]  4  while low < high  5  mid = (low + high) >> 1  6  val = list[mid]  7  return mid if val is target  8  if val < target then low = mid + 1 else high = mid  9  return -1 

This is a quick implementation of a binary search. Don't try to parse the code itself right now. Just try to familiarize yourselves with the syntax.

Below is the JavaScript code that CoffeeScript generates:

 1 2 var index;  3 index = function(list, target) {  4  var high, low, mid, val, _ref;  5  _ref = [0, list.length], low = _ref[0], high = _ref[1];  6  while (low < high) {  7  mid = (low + high) >> 1;  8  val = list[mid];  9  if (val === target) {  10  return mid;  11  }  12  if (val < target) {  13  low = mid + 1;  14  } else {  15  high = mid;  16  }  17  }  18  return -1;  19 }; 

Pros and Cons

Here are some quick advantages and disadvantages of using CoffeeScript. This isn't comprehensive by any means but I think this is sufficient to get a quick overview of the system.

Yays

• Python style whitespacing
• Ruby styled lightweight syntax
• Concise function declarations
• JSLint approved
• Class based inheritance

There are, of course, numerous other points including semantic and syntactic enhancements.

Nays

• Slight learning curve involved
• Deployment, depending on your route, may be a chore
• You'll need a basic knowledge of JS for debugging purposes. You can't directly start here, naturally.

Getting Started

The official methods to get started include a command line utility that runs under node.js and simply downloading the source and installing it. Nothing much to guide here. Get the node.js utility and use npm install coffee-script [or for the source, bin/cake install] to install and get started.

The situation with Windows is slightly more complicated. There is no straight forward way to get node.js or the source installed on Windows [outside of Cygwin]. Never fret though. A number of enterprising people have written compilers that work natively on Windows. I've included a few below:

Note that the compiler, in compiled JavaScript form, is also bundled with the source, if you're interested. It's present under the extra directory with an obvious name.

With that out of the way, we're now going to take a look at a handful of things that show you how CoffeeScript makes JavaScript easier to consume!

Use of Whitespace

The first thing you'll need to know is how CoffeeScript uses whitespace effectively to simplify the syntax. People with a Python background will find this trivial but for the others, here is a quick explanation.

First up, you need not end every line with a semi-colon. Ending a line is automatically interpreted to be the end of that statement. For example, this..

 1 2 numbers = [0, 1, 2, 3]  3 name = "NetTuts+" 

.. compiles down to this:

 1 2 var name, numbers;  3 numbers = [0, 1, 2, 3];  4 name = "NetTuts+"; 

Next, you'll be happy to know that you can do away with curly braces. Those numerous braces for opening and closing a block? Everything's out. In CoffeeScript, you use Python-esque indentation to signify the beginning and ending of a block.

CoffeeScript doesn't require unnecessary parentheses or curly braces.

Here is a quick example. Disregard everything but the indentation for now. We'll get to the rest a little later below:

 1 2 if chasedByCylons  3  runForYourLife() 

.. compiles down to

 1 2 if (chasedByCylons) {  3  runForYourLife();  4 } 

If you're still a little confused, don't worry. The syntax will start making more sense once we get to know the language better.

Nifty, Semantic Aliases

CoffeeScript provides a number of aliases for operators and keywords to make the code more readable and intuitive. Let's take a look at some of them now.

First, the comparison operators:

• is maps to ===
• isnt compiles to !==
• == and != compile to === and !== respectively [As a best practice]

Let's see them in action quickly.

 1 2 if pant is onFire  3  lookForWater()  4 5 if game isnt good  6  badMouth(); 

..which compiles to..

 1 2 if (pant === onFire) {  3  lookForWater();  4 }  5 if (game !== good) {  6  badMouth();  7 } 

Pretty easy to read, no? Now, on to how logical operators are mapped.

• and maps to &&
• or is an alias for ||
• not compiles down to !

Building on our previous code:

 1 2 if pant is onFire and not aDream  3  lookForWater()  4 5 if game isnt good or haughtyDevs  6  badMouth(); 

..which compiles to..

 1 2 if (pant === onFire && !aDream) {  3  lookForWater();  4 }  5 if (game !== good || haughtyDevs) {  6  badMouth();  7 } 

Conditionals

As you've already seen above, the basic if/else construct behaves the same as in normal JavaScript, sans the parentheses and curly braces. We'll look at some variations below.

 1 2 if tired and bored  3  sleep()  4 else  5  jog()  6   7 // Raw JS below  8 9 if (tired && bored) {  10  sleep();  11 } else {  12  jog();  13 } 

And here's how the ternary operator is handled:

 1 2 activity = if sunday then isChilling else isWorking  3   4 // Raw JS below  5 6 activity = sunday ? isChilling : isWorking; 

An additional semantic enhancement is with the unless keyword. This functions as the exact opposite of if.

 1 2 keepRunning() unless tired  3 4 keepWorking unless focus is extremelyLow 

And the compiled JavaScript...

 1 2 if (!tired) {  3  keepRunning();  4 }  5 if (focus !== extremelyLow) {  6  keepWorking;  7 } 

Switch-Case

Switch statements can be a little obtuse in JavaScript. CoffeeScript provides an intuitive wrapper around this construct.

It begins with the switch keyword, as expected, followed by the variable whose value we're checking. Each case or possible value is preceded by the when keyword followed by the statements to execute if it's a match.

There's no need to add a break statement at the end of every case statement: CoffeeScript does this automatically for you.

 1 2 switch time  3  when 6.00  4  wakeUp()  5  jotDownList()  6  when 9.00 then startWorking()  7  when 13.00 then eat()  8  when 23.00  9  finishUpWork()  10  sleep()  11  else doNothing() 

The syntax should be fairly self explanatory if you already know the equivalent in JavaScript. The only point to note here is the use of the then keyword. It's used to separate the condition from the expression without starting a new line. You can use then for the other conditional statements as well as loops too.

Here's the JS that CoffeeScript generates for you:

 1 2 switch (time) {  3  case 6.00:  4  wakeUp();  5  jotDownList();  6  break;  7  case 9.00:  8  startWorking();  9  break;  10  case 13.00:  11  eat();  12  break;  13  case 23.00:  14  finishUpWork();  15  sleep();  16  break;  17  default:  18  doNothing();  19 } 

Basic Loops

Looping is another essential construct for your typical JavaScript code. Be it looping through numbers in an array or nodes in the DOM, you're always in need of looping through collections.

CoffeeScript provides a very flexible while loop that can be modified to function as a generic for or do-while loop.

 1 2 while work > time then freakOut()  3 4 while time > work  5  relax()  6  mozyAround()  7 8 // Raw JS  9 10 while (work > time) {  11  freakOut();  12 }  13 while (time > work) {  14  relax();  15  mozyAround();  16 } 

until is another semantic enhancement and is equivalent to while not. A quick example below:

 1 2 workOut() until energy < exhaustion  3 4 // Raw JS  5 6 while (!(energy < exhaustion)) {  7  workOut();  8 } 

Looping Through Collections

Looping over arrays is pretty easy. You'll need to use the for..in construct to step through the array. Let me show you how:

 1 2 sites = ['CodeCanyon','ThemeForest','ActiveDen']  3 for site in sites  4  alert site 

If you prefer the statements to be in the same line:

 1 2 sites = ['CodeCanyon','ThemeForest','ActiveDen']  3 alert site for site in sites 

CoffeeScripts compiles these to basic for loops like so. Note that in line with best practices, the length of the array is cached beforehand.

 1 2 var site, sites, _i, _len;  3 sites = ['CodeCanyon', 'ThemeForest', 'ActiveDen'];  4 for (_i = 0, _len = sites.length; _i < _len; _i++) {  5  site = sites[_i];  6  alert(site);  7 } 

Iterating over associate arrays [or hashes or dictionaries or key-value pairs] is just as easy with the of keyword.

 1 2 managers = 'CodeCanyon': 'Jeffrey Way', 'ThemeForest': 'Mark Brodhuber', 'ActiveDen': 'Lance Snider'  3 4 for site, manager of managers  5  alert manager + " manages " + site 

As expected, the above compiles down to a basic for loop as shown below:

 1 2 var manager, managers, site;  3 managers = {  4  'CodeCanyon': 'Jeffrey Way',  5  'ThemeForest': 'Mark Brodhuber',  6  'ActiveDen': 'Lance Snider'  7 };  8 for (site in managers) {  9  manager = managers[site];  10  alert(manager + " manages " + site);  11 } 

Functions

Creating and using functions is extremely easy under CoffeeScript. To define a function, you list the parameters it takes and then go on with the function's body. Here, let me show you how:

 1 2 playing = (console, game = "Mass Effect") ->  3  alert "Playing #{game} on my #{console}."  4 5 playing 'Xbox 360', 'New Vegas' 

This is the basic syntax behind creating and using functions. The default value for parameters can be defined inline. CoffeeScript generates the code to check whether a value has been passed in or not.

Invoking a function is just as easy. There's no need for parentheses: pass in the parameters one after the other.

As always, here's the generated code for your reference:

 1 2 var playing;  3 playing = function(console, game) {  4  if (game == null) {  5  game = "Mass Effect";  6  }  7  return alert("Playing " + game + " on my " + console + ".");  8 };  9 playing('Xbox 360', 'New Vegas'); 

Embedding Raw JavaScript

Sometimes, you may have no other choice but to use raw JavaScript inside your CoffeeScript code. Hopefully, these instances should be far and few between but this has been taken into account as well.

You can inject raw JS into your code by wrapping it with grave accents, also known as a backquote or backtick. Anything passed in thus will be completely untouched by the CoffeeScript compiler.

 1 2 rawJS = function() {  3  return someSuperComplexThingie;  4 }  5 6 // which nets you  7 8 var rawJS;  9 rawJS = function() {  10  return someSuperComplexThingie;  11 }; 

What Happens to My Libraries?

Nothing happens to them, they can stay exactly where they are. CoffeeScript works seamlessly with any third party library, big or small, because it simply compiles to raw JavaScript. You'll just have to reformat and/or refactor your code very slightly but other than that, incompatibilities shouldn't be a point of concern.

So instead of writing this:

 1 2 $(document).ready(function() {  3  elemCollection =$('.collection');  4  for (i=0; i<=elemCollection.length;i++)  5  {  6  item = elemCollection[i];  7  // check for some random property here. I am skipping the check here  8  colortoAdd = item.hasProperty()? yesColor : noColor;  9  // I'm quite aware there are better ways to do this  10  $(item).css ('background-color', colortoAdd);  11  }  12 });  ... you'd write..  1 2 $(document).ready ->  3  elemCollection = $('.collection')  4  for item in elemCollection  5  colortoAdd = if item.hasProperty() then yesColor else noColor  6 $(item).css 'background-color', colortoAdd 

That's All Folks

And we've come to an end. I haven't covered a number of higher levels topics, classes for example, because they're well beyond the scope of an introductory article. Look for some advanced CoffeeScript tutorials down the road!

I think CoffeeScript has changed the way I write JavaScript and, after reading this, I hope it has changed yours too. Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding and thank you so much for reading!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.