Try Tuts+ Premium, Get Cash Back!
Rocking Out With CoffeeScript

Rocking Out With CoffeeScript

Tutorial Details
  • Topic: CoffeeScript, JavaScript
  • Difficulty: Intermediate
  • Estimated completion time: 30 minutes
  • Post Graphic: Available at GraphicRiver

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:

index = (list, target) ->
  [low, high] = [0, list.length]
  while low < high
    mid = (low + high) >> 1
    val = list[mid]
    return mid if val is target
    if val < target then low = mid + 1 else high = mid
  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:

var index;
index = function(list, target) {
  var high, low, mid, val, _ref;
  _ref = [0, list.length], low = _ref[0], high = _ref[1];
  while (low < high) {
    mid = (low + high) >> 1;
    val = list[mid];
    if (val === target) {
      return mid;
    }
    if (val < target) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return -1;
};

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..

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

.. compiles down to this:

var name, numbers;
numbers = [0, 1, 2, 3];
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:

if chasedByCylons
 runForYourLife()

.. compiles down to

if (chasedByCylons) {
  runForYourLife();
} 

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.

if pant is onFire
 lookForWater()

if game isnt good
 badMouth();

..which compiles to..

if (pant === onFire) {
  lookForWater();
}
if (game !== good) {
  badMouth();
}

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:

if pant is onFire and not aDream
 lookForWater()

if game isnt good or haughtyDevs
 badMouth();

..which compiles to..

if (pant === onFire && !aDream) {
  lookForWater();
}
if (game !== good || haughtyDevs) {
  badMouth();
}

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.

if tired and bored
 sleep()
else 
 jog()
 
// Raw JS below

if (tired && bored) {
  sleep();
} else {
  jog();
}

And here’s how the ternary operator is handled:

activity = if sunday then isChilling else isWorking
 
// Raw JS below

activity = sunday ? isChilling : isWorking;

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

keepRunning() unless tired

keepWorking unless focus is extremelyLow

And the compiled JavaScript…

if (!tired) {
  keepRunning();
}
if (focus !== extremelyLow) {
  keepWorking;
}

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.

switch time
 when 6.00 
  wakeUp()
  jotDownList()
 when 9.00 then startWorking()
 when 13.00 then eat()
 when 23.00
  finishUpWork()
  sleep()
 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:

switch (time) {
  case 6.00:
    wakeUp();
    jotDownList();
    break;
  case 9.00:
    startWorking();
    break;
  case 13.00:
    eat();
    break;
  case 23.00:
    finishUpWork();
    sleep();
    break;
  default:
    doNothing();
}

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.

while work > time then freakOut()

while time > work 
  relax()
  mozyAround()

// Raw JS

while (work > time) {
  freakOut();
}
while (time > work) {
  relax();
  mozyAround();
}

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

workOut() until energy < exhaustion 

// Raw JS

while (!(energy < exhaustion)) {
  workOut();
}

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:

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

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

sites = ['CodeCanyon','ThemeForest','ActiveDen']
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.

var site, sites, _i, _len;
sites = ['CodeCanyon', 'ThemeForest', 'ActiveDen'];
for (_i = 0, _len = sites.length; _i < _len; _i++) {
  site = sites[_i];
  alert(site);
}

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

managers = 'CodeCanyon': 'Jeffrey Way', 'ThemeForest': 'Mark Brodhuber', 'ActiveDen': 'Lance Snider'

for site, manager of managers
  alert manager + " manages " + site

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

var manager, managers, site;
managers = {
  'CodeCanyon': 'Jeffrey Way',
  'ThemeForest': 'Mark Brodhuber',
  'ActiveDen': 'Lance Snider'
};
for (site in managers) {
  manager = managers[site];
  alert(manager + " manages " + site);
}

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:

playing = (console, game = "Mass Effect") ->
  alert "Playing #{game} on my #{console}."

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:

var playing;
playing = function(console, game) {
  if (game == null) {
    game = "Mass Effect";
  }
  return alert("Playing " + game + " on my " + console + ".");
};
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.

rawJS = `function() {
  return someSuperComplexThingie;
}`

// which nets you

var rawJS;
rawJS = function() {
  return someSuperComplexThingie;
};

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:

$(document).ready(function() {
 elemCollection = $('.collection');
  for (i=0; i<=elemCollection.length;i++)
  {
    item = elemCollection[i];
   // check for some random property here. I am skipping the check here  
   colortoAdd = item.hasProperty()? yesColor : noColor;
   // I'm quite aware there are better ways to do this 
   $(item).css ('background-color', colortoAdd);
  }
});

... you'd write..

$(document).ready ->
    elemCollection = $('.collection')
    for item in elemCollection    
      colortoAdd = if item.hasProperty() then yesColor else noColor
      $(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!

Siddharth is Siddharth on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Abhijit

    Looks interesting. Did not know about. Will give it a try. Thanks for sharing!

    • http://www.ssiddharth.com Siddharth
      Author

      And thank you for reading. :)

  • http://www.jc-designs.net/blog Jeremy Carlson

    While I have no problems with abstraction what-so-ever, because I love Sass (and Haml looks good too!), I have a hard time convincing myself to actually try this one. I read about CoffeeScript a while ago, and thought “This is awesome!” And it is, if you know straight js. But I write jQuery, and while CoffeeS. does abstract jQuery, my limit is reached in that I think shortening up the syntax even further becomes slightly ridiculous. jQuery is quick to write as it is, and this will just confuse things more for me.

    If all I knew was hard core javascript, this would be a dream come true. I honestly don’t see this catching on all that well though. I have read heated arguments between developers that hate jQuery, and if they hate that, they are not going to like this. I think there are people that like to write out the long complicated syntax and see anything that takes that away as a bastardization. The others that love jQuery, I can see staying away because they’ll say the same thing I did. It’s already quick to write, why take the time to learn an abstraction of an abstraction.

    I wrote an article about abstraction languages that might be interesting for you guys about this type of thing:
    http://jc-designs.net/blog/2010/12/abstraction-of-web-development-languages/

    • http://www.ssiddharth.com Siddharth
      Author

      jQuery and CoffeeScript handle entirely different things. Just because someone hates jQuery doesn’t mean he is going to hate CoffeeScript as well.

      CS abstracts some of the tediousness of the language itself, not the browser environment, which jQuery handles.

      Thanks for reading!

      • http://www.jc-designs.net/blog Jeremy Carlson

        As to your first statement, this is true. But I know a few people who hate jQuery because they don’t think it is as ‘readable’ as straight js. Has nothing to do with what it does.

        Your second statement, I know CS abstracts js. I wasn’t talking about what jQuery handles. My main point was, jQuery is fast as hell to write as it is, and now you want to abstract that further by taking out all the garbage syntax, which to me reduces the instant readability. If you are using CS to write jQuery, you are writing an abstraction of an abstraction.

        Trust me, I get the advantages of CS. I use Sass when building my personal projects, but I use SCSS syntax. I prefer the newer syntax because it is written more like CSS and is more readable to me, while keeping all the added functionality that Sass has. I assume that CS adds more than just taking out the ‘annoying’ syntax, I just don’t see this becoming more than a ‘cool, let’s try that out once’ type of thing.

      • http://www.ssiddharth.com Siddharth
        Author

        Yep, I concur about the dual abstractions. Writing jQuery code in CS can be a little troublesome to parse. I just added that bit to show that it doesn’t break compatibility and can be used with other libraries when needed.

        I see CS primarily to be of greater use in web applications as opposed to web sites. I’ve been using CS with Backbone and it has been a lot of fun!

  • http://www.moviemusicgame.com mmgfan

    Coffee vs Java
    Java coffee is a coffee produced on the island of Java. In the United States the term “Java” by itself is, in general, slang for coffee. from wiki http://en.wikipedia.org/wiki/Java_coffee
    Interesting!

  • Mike Hopley

    I suppose this is nice for people who dabble in javascript but mainly write Python and Ruby.

    Personally, I don’t see the point. Why add a compilation step, just for some minor syntactic differences? Why does javascript need to look like some other language?

    I find this stuff a bit obsessive-compulsive. Reducing typing is much less useful than programmers tend to think. Programmers — or web developers — spend very little time typing, as a proportion.

    Is it more readable? Possibly, depending on what you’re used to. It’s certainly shorter, but shorter isn’t always more readable.

    I’d argue that CoffeeScript makes debugging slower, because you have to “match up” the compiled javascript (which you are debugging) against the CoffeeScript source (which you are changing). This is likely to waste more time than you could save from CoffeeScript’s terser syntax. For one thing, the line numbers won’t match up — and this annoyance becomes progressively worse with longer files.

    Don’t get me wrong: it’s great that tools like CoffeeScript are available; it’s a sign of maturity in the discipline. But to my mind, this one complicates more than it simplifies.

    • http://www.profilepicture.co.uk Phil

      Couldn’t agree more!

      JavaScript is a fast language to code in due to the fact that it is interpreted, adding the compilation step to get rid of some curly braces and parenthesis doesn’t do it for me at all.

    • http://apps.rflab.co.za/convertor/ Q_theDreadlockedNinja

      Also couldn’t agree with you more, my back-end language of choice is PHP and i find CoffeeScript very annoying. If you have taken time to learn JavaScript you will appreciate the good practice of well formed spacing, curly braces and semi-colons.

    • Jason

      I also agree here. Coffeescript looks interesting however it looks like a redundant innovation for the reasons Mike mentioned above.

    • http://elfsternberg.com Elf M. Sternberg

      My biggest problem with CoffeeScript is that it limits you to what CoffeeScript is capable of. If CoffeeScript can’t do it, you’ll either have to write in in JS and include it as a library, or you’ll have to find some work-around, or you’ll have to abandon CoffeeScript altogether.

      I had a very (very!) large Backbone.JS framework with collections and models that reached down through seven levels of objects, and had cross-references and weak references all throughout. It had a reliable RESTful mode, a schema and a working UML Class Diagram… and I could not express the relationships in CoffeeScript without either using all-global variables, or passing around insane amounts of data.

      I eventually ended up managing my own scopes, thank you very much, in Javascript. I still use Backbone and Underscore, and even Futures, but CoffeeScript remains very much in the background, limited by its lack of expressive clarity when it comes to scope.

  • chad

    This looks really good, however you haven’t showed how to execute any of this via the coffee command from terminal to at least get the compiled file.

    • http://www.ssiddharth.com Siddharth
      Author

      I initially thought of adding this step but decided it was too basic. Create your .coffee file, pass it to the command line compiler and you’re done.

      Thanks for reading!

  • http://www.jakswebdesign.com Adam

    Looks like a potentially huge productivity booster….although some of your clever function and variable names probably over-inflated the “ease of readability” that CoffeeScript provides, it still looks quite valuable. Excellent tut!

  • http://hultner.se Alexander Hultner

    While I like the idea this isn’t for me. As I am an C and then C++ programmer form the start and only moved on to the web with PHP, JavaScript, Java and html, css after that I am more used to the curly braces and parenthesis based syntax then the Ruby/Python-ilke syntax, it adds structure and readability for me. So for me plain JavaScript is easier, just like I write Perl faster then Ruby. But this is probably great for some people just not for me.

  • http://coffeescript.org Jeremy Ashkenas

    @Mike, @Jeremy –

    This particular tutorial talks about some of the syntactic differences, which — agreed — aren’t *terribly* important. There are, however, a number of more important semantic differences which aren’t mentioned in this tutorial:

    * Everything is an expression in CoffeeScript. Everything that would be a statement in JavaScript can be used in an assignment, or passed to a function call, or returned as a value, in CoffeeScript.

    * Splats let you have nice variadic functions without having to muck with the arguments object.

    * Default arguments provide a nice way to have functions take optional arguments with default values.

    * List and Object comprehensions make it really easy to map arrays and objects, without writing a “for” loop:

    doubled = (x * 2 for x in numbers)

    * The existential operator allows you to check for the existence of a value in JS, which would otherwise be tricky, because the empty string “”, “NaN”, “0″, all evaluate to “false” in JS.

    * All variables are automatically lexically scoped, so you can never create global variables by accident, and don’t have to ever write “var”.

    * CoffeeScript provides simple classes, which take the headache out of trying to set up the prototype chain yourself.

    That’s off the top of my head — there are a bunch more, with examples, at coffeescript.org

    • http://www.ssiddharth.com Siddharth
      Author

      Hey Jeremy, thanks for stopping by!

      I initially wanted to mention all the features [splats, for instance, are pretty nifty!] but since this is a getting started guide, decided against it.

      I’ve also sent an email regarding doing a possible followup to this.

      @everyone – Jeremy is the awesome guy behind CoffeeScript.

  • z_kagenotora

    It seems interesting. Depends on its flexibility (in term of library, plugin etc..), it’s flexible enough, i’m speculating that it might be able to replace JS.

  • PandaWood

    Yes, those who think CoffeeScript offers only minor syntactic differences may have been led slightly astray.
    I use all coffeescript on my web site now because writing 30% less code does have some appeal.

    Unfortunately, this tutorial leaves out nearly all the killer reasons I use coffeescript.

    One is called ‘interpolation’ (it works like ruby’s interpolation if you need to google it) – and if you consider this minor syntactic sugar, then we have a problem:

    Here’s some coffeescript code:

    scoreMessage = “You scored #{score}/#{length} (#{Math.floor(score*100/length)}%)”

    javascript:

    var scoreMessage = (“You scored ” + score + “/” + length + ” (” + (Math.floor(score * 100 / length)) + “%)”);

    The javascript version is the sort of code you should never want to maintain.
    And it gets worse the more code you write:

    coffeescript:

    quizHtml +=
    “<span id=\”#{index+1}\” class=\”quizAnswer\”>
    <label for=\”#{labelId}\”>#{answer}</label>
    <input id=\”#{labelId}\” type=\”radio\” name=\”a\”></input>
    </span>”

    javascript:

    quizHtml += (“<span id=\”" + (index + 1) + “\” class=\”quizAnswer\”>\
    <label for=\”" + (labelId) + “\”>” + (answer) + “</label>\
    <input id=\”" + (labelId) + “\” type=\”radio\” name=\”a\”></input>\
    </span>”);

    • http://www.ssiddharth.com Siddharth
      Author

      Hey Panda, good points. I wanted to cover these as well but decided it’d make this article too verbose. Expect a follow up post pretty soon!

      Thanks for reading!

  • PandaWood

    Can I also suggest another way to get coffeescript to work on windows:
    jcoffeescript: https://github.com/yeungda/jcoffeescript

    I need to use this to get the option to “–no-wrap” which the CoffeeScript-Compiler-for-Windows is hard-coded to not do.

    It also looks like jcoffeescript would be easier to modify in order to implement the remaining command-line options for coffeescript eg ‘watch’ – which I would really like.

  • http://nathansweet.me Nathan Sweet

    My question is: Why wouldn’t you want to learn JavaScript? Just because you’re a Ruby or Python programmer (which is the only reason I can see using this…if you know JavaScript well, why on earth would you learn this) it doesn’t mean that you shouldn’t expand your horizons. Learning another language will make you a better programmer.
    Implementing a whole new class system is also kind of weird, because if people are really making classes with JavaScript they should either a) know the DOM insanely well, in which case they should also know JavaScript well or b) use a JavaScript library to handle the DOM trickery for them, in which case they could just learn JavaScript moderately well and learn the library (which they have to anyway, even if they use CoffeeScript).
    Also, you limit some of JavaScript by limiting it to what Douglas Crockford (JSLint) thinks it should be. Is getting rid of of the “Lint” a good thing usually? Yes! Is it always? No! There are some legitimately useful things JavaScript can do that aren’t JSLInt approved. For example, I’ve seen people write insanely inefficient code, just so they wouldn’t have to create a global variable. Just some thoughts. This looks very useful if you’re coming in from Python or Ruby though and you don’t have time to get up to speed on JS.

    • jsc42

      Classes in JavaScript are not related to the DOM. They are part of the language even when not running in a browser.

      Classes using inheritance can be implemented in JavaScript as an adjunct to the prototyping form of objects. Most people know that many JS classes inherit from Object. However, the inheritance model, although not intrinsically difficult, is syntactically convoluted for novice JS programmers and is a good case where ‘syntactic sugar’ can save a lot of effort.

      Even the new features in ECMAScript 5 which are designed to make the inheritance model more intuitive do not really make it that much clearer.

      • http://nathansweet.me Nathan Sweet

        My point wasn’t that classes are an inherent part of the DOM, but that someone who is constructing a class is probably doing so for some reason to DO with the DOM. Examples: A class to handle the google maps api, ajax classes, advanced xml manipulation, etc, etc. Nowadays its really hard to find JavaScript that isn’t advanced/library based. If we randomly picked 7 sites on the internet right now, chances are they would be using a JavaScript library. Advanced DOM manipulation is part of the everyday web now. Making code that can be reusable and readable for this advanced manipulation almost always involves classes. If you’re not using a library than you have to know the DOM well.

        My basic observation, then, is if you are using a library as a novice JS developer (which is likely) then you have to learn that library first. That’s a no-brainer. Along the way of learning any given JavaScript library, you are, variably, learning JavaScript. Why bother with something else when you have to know the library well anyways, follow its coding examples, practices, etc. Most people aren’t going to want to learn another language (CoffeeScript) to do all of that, because they’ll have to still get to know JavaScript anyways, so they won’t see the payoff.

  • Mike Hopley

    I see that CoffeeScript is more substantial than this article suggested.

    I’m still not sure whether it’s useful to me, but it’s been upgraded from “syntactic sugar” to “possibly worthwhile”.

    If you’re embedding lots of HTML in your javascript, however, I would have thought templates were the solution, not CoffeeScript (e.g. http://api.jquery.com/category/plugins/templates/ ).

  • gopal

    how about multiple loops….it works???

    • http://www.ssiddharth.com Siddharth
      Author

      I don’t see why it shouldn’t. :)

  • Bill Woodruff

    Interesting article, well written.

    I have three reactions:

    1. if you are going after “less typing” as a guiding value: why not eliminate the empty parens after a function call with no arguments, or replace the two parens (requiring top row typing) with some one character (an asterisk ?)

    2. The code example:

    managers = ‘CodeCanyon’: ‘Jeffrey Way’, ‘ThemeForest’: ‘Mark Brodhuber’, ‘ActiveDen’: ‘Lance Snider’
    for site, manager of managers
    alert manager + ” manages ” + site

    Something about the comma after “for site” seems weird to me: is this a typo ?

    3. the problem in real world usage I can imagine is :

    a. I write JS in CS: compile it to raw JS.

    b. I plug in the raw JS into some complex site code using jQuery and HTML, and I test and I find a bug in the JavaScript (meaning I a bug in my code, not a bug caused by CS)

    The outcome is I have to go back to CS, fix the bug there, re-compile, re-insert, and test again. That could be costly in terms of time.

    Thanks very much for this article,

    best, Bill

    • http://www.ssiddharth.com Siddharth
      Author

      Nope, it’s not a typo. You can copy the CS code and run it through the compiler on the CS site. It’s essentially mapping the variables to the key-value pair in the hash.

      And optimally, you’d set up a system to auto-compile the CS file and link it to your front end. Recompiling and reinserting each time would be incredibly time consuming and pointless.

      Thanks for reading!

  • mayjune

    Really nice…
    Thanks a lot

  • bill

    “Today, we’re going to take a look at why everyone is talking about CoffeeScript.”

    You’re the first person I’ve ever heard mention it.

    • David Murphy

      I agree, never heard of it before. Capuccino seems better established and with an Objective-C like language above JS if one wants to code for JS but not in JS.

      • http://www.ssiddharth.com Siddharth
        Author

        No, you’ve missed the point. Capuccino and CoffeeScript handle entirely different things. Cappucino is a framework for writing full stack front end for web applications, similar to SproutCore.

        Cappuccino is an abstraction that takes away some of the idiosyncrasies of JavaScript. Apples and oranges, mate. :)

    • http://www.twitter.com/evilmeteor Jaime

      If you haven’t heard of it then you’re not keeping up with the times buddy. :)

      • bill

        I’m not your buddy pal.

  • http://www.mdrisser.com mdrisser

    I have to agree with the majority of the commenters here, while its an interesting idea, why jump through all the hoops? As Mike Hopley mentioned above, debugging the code would be a nightmare. In order to do any meaningful debugging, you’re going to have to learn/know JavaScript anyway, so why add the extra steps? That just doesn’t seem very efficient.

    @z_kagenotora I’m sorry, but unless browsers implement a CS engine, I can’t see how this could replace JS. It still compiles down to JS, which, as I said, you’re still going to have to know in order to do any meaningful debugging.

    Personally, I’m comfortable with the curly braces and other syntactic devices used by JS, it is after all a C based language, like C++, PHP, Java, Perl, etc. Don’t get me wrong, I like Python and Ruby. They have their strengths and weaknesses, just like any other language, but CS? I’m just not sure that the extra steps needed to get to something else is really worth it.

    @Jeremy Ashkenas, in all fairness, the fact that you came up with this is, in and of its self, simply brilliant.

  • http://www.brainstormstudio.com Brainstorm

    Really Great Article, Thanks

  • Tyler

    This is the first I’ve heard of it, too.

  • bill

    hmm. Maybe I’m unusual, but I’m still not overly attracted to Python’s use of indentation. :P

  • http://comedysportz.com Br.Bill

    It’s funny to me that “Python-like whitespace” is described as a feature.

    It’s a property. A quality. An attribute. But a feature?

    That’s like describing EOS semicolons as a “feature” of javascript.

    Hope this makes sense. But what do I know, I think in pure Perl.

  • http://createmy.com.au Dale Hurley

    Yep, first I heard of it too.

    Honestly, it sounds like a good idea though not very practical. Maybe the author did not explain it right???

    Flicking through the CoffeeScript site, the clear advantage they are pushing is well formed JS and that JS is too hard to read. I would argue that the JS they are aiming for is too hard to read not that real world JS is too hard to read.

    I think it is something to geek out on for some learning but not really practical for real-world web development.

  • Sebastien

    Is everyone really talking about CoffeeScript? Never heard of it…

    Well, why should I get ride of curly braces and semicolons? I add them even when not mandatory for readability and debugging purpose. I think there are much more useful things to learn than another layer for javascript :p
    Thanks anyway. Very informative article.

  • http://brianegan.com Brian Egan

    For those that are interested & use Vim, there’s a great Vim plugin:

    https://github.com/kchmck/vim-coffee-script

    It not only does all the usual goodness like syntax highlighting and taking care of whitespace with proper indenting, you can also add the following option to your .vimrc:

    let coffee_compile_on_save = 1

    And the plugin will auto-compile your .coffeescript into .js every time you save!

    ProTip: Follow the instructions to install using Pathogen. Pathogen is money.

    • http://www.ssiddharth.com Siddharth
      Author

      Money in the bank, sir! Good tip. :)

  • João Lopes

    I stop reading after the statement
    “There’s no need to add a break statement at the end of every case statement: CoffeeScript does this automatically for you.”
    Where is that a good thing?
    Not always i want breaks…

    • http://www.ssiddharth.com Siddharth
      Author

      Adding a breaking when there are >5 cases to check is actually quite a chore. And missing one can be catastrophic. I like my syntactic sugar.

  • Edison Leon

    Humm, new to me, and interesting Thanks for the intro

  • Greg

    Sorry friend, but after coding JS for years I’m not going to learn a new language just because someone thought it would be cool to wrap a well known, standard based language with new syntax, or under the not-so-convincing premise of writing short code, besides, 2 awful things: 1- Syntax is like Perl/Ruby wich I hate with all my heart 2- the code must get compiled, this add an extra step in the development process and waste my little time.

    Sorry, but is the truth, at least for me.

  • http://www.thedevelopertuts.com Bratu Sebastian

    Every time there’s an idea, you can implement it. Cofee is just another project aimed at making the work of a developer easier. For a beginner it helps.

    There’s a lot of disagreement about why would code in the same language dialect. Of course, nobody is encouraging you to do anything, for professionals will always prefere raw coding + texteditor over complicated cms or metalanguages.

    There are a lot of new concepts appearing every day. Its hard to find out that there’s a new fancy way of doing something every other day and that attacks a developer’s personal trust, thus making you angry at all these new tech shortcuts.

    So, don’t worry if you’re a programmer and you know the original language, no new shortcut will make it better ( although some shortcuts will get you faster at the restaurant in the evening ).

    Nice tutorial, anyway, I read it with pleasure!

  • http://www.arisb.gr/ Aris

    Thumbs up !

  • http://boliviaonrails.com Boris Barroso

    Great. Iove coffee-script I have improved my productivity since I used it, it makes things so much nicer to read, and the biggest part of development is READING code. I see many people that do not like for many reasons, many might not want to give coffee-script a good try, but I would recomend all to really give it a good try and it might surprise you.

  • Naviciroel

    Its seems interesting but as Mike Hopley said its obsessive-compulsive. From my point of view CS doesn’t seem to have a good impression.

    CS may look easy to lean but tracing scripts without curly brackets is insane…….

  • http://morgancraft.com morgan craft

    In your Switch-Case I don’t think your generated javascript is correct. Coffeescript is supposed to return a if/else-if structure because switch is broken in javascript and can only evaluate strings. By returning a if/else-if structure the code can then interpret other data types. I’m no expert and haven’t actually used coffeescript, just researching it and while watching Jeremy’s video http://jsconf.blip.tv/file/3735066?filename=Voodootikigod-JeremyAshkenasJSConf2010TrackB939.flv I literally was watching the part about switch when I read your portion of this article and noticed it might not be correct.

  • Paul

    Perhaps I’m a little late but my personal statistics are as such:

    A quick Javascript code test was: 118 lines | 310 words | 4033 bytes
    CoffeeScript generated it with: 86 lines | 246 words | 3331 bytes

    note: one curly brace “{” is counted as a word

    around 25% savings and CS seems a little easy to read.

  • leptons

    CoffeeScript has proven to be a tool for noobs who don’t know what they are doing. It seems like a good idea at first to the noob, but this is snake oil. It isn’t going to improve your javascript coding abilities. It will get in the way of developing good clean javascript code. The time you waste learning coffeescript and fussing with debugging it jumping through multiple hoops could better be spent just learning javascript. Coffeescript is a not net positive in terms of productivity. You have to take a look at the entire development cycle and realize that you are going to waste more time by using coffeescript than you would if you just used javascript.

  • Will

    This is a great concept. The frist OO languages used these techniques building a new language atop an original. There used to be a OO /Simulation language called Simscript — I had a FORTRAN translator to compiler itself into FORTRAN and volia! You have an OO system simulated. And again with Simula and C++. It is a great method to leverage good technology to get better. And an brother to DSL-s.

    For myself, I’m encouraged to consider what kind of meta-level code use I could implement if I step back and think about the way these techniques could empower the conceptual level of the build/develop and maintain cycle. Excellent inspiration.

    w.

  • shadow skill

    First off syntactic whitespace is never ever a good idea. No one leaves off the punctuations in English and claims that this is “beautiful” when you are trying to use the language to communicate an idea, since the lack of punctuations creates ambiguity. You will almost never see prefix or postfix style notation for mathematics because both of these notations create difficulties in determining what the operands are visually. No being able to use a computer to prove that “/ 5 43″ is in fact “5/43″ and not “54/3″ does not make this problem go away. In the same way a computer does not obviate the need for the existence of operator precedence when dealing with infix notation. (The standard we normally use.) Syntactic whitespace makes things harder to understand since you can never be 100% sure what your scope is visually since spacing is rendered differently on different machines.

    Coffeescript is a good idea but optimizing for writing as opposed to reading by using whitespace in the manner it does really creates a barrier to understanding, as well as practical issues with copy and paste or other programs easily destroying the semantics of a script because of how spaces or tabs are handled.

    Coffeescript should be more like a DSL that simply drops into languages like Ruby, Python, or C#/VB.net and extends those languages with tools to create Javascript using the native syntax of those languages. In other words it would be equivalent to Entity Framework in .net or Sequel and/or ActiveRecord in Ruby. I would think such a DSL would work even better than ORMs do since you don’t have to deal with the complication that SQL presents because data does not technically have state.

    I’m not primarily a web developer so I have not needed to learn JavaScript until recently and I have to say that I do not want to really learn a new language just to get a drop down list to fire an event and fill in a form just because that takes time away from me actually delivering my application. I want to write the event handler from the same language I used to connect to SQL server and process the datasets returned by that server.

    Don’t get me wrong learning a language as an exercise is something I like doing, I just don’t want to do that when I am trying to get things done.

  • http://eric.muyser.com/ Eric

    I’ve known JavaScript for quite and a while, and CoffeeScript is a blessing. Thanks for the article Siddharth.

    This isn’t about syntactical differences. This is about safe and self-explanatory code. This is about the Good Stuff ™. Have you not seen Crockford’s criticisms? They are entirely valid, IMHO, but JSLint is no great solution either. I know the problems with JavaScript, and when I see how CoffeeScript is deconstructed, it makes perfect sense.

    Do you write JavaScript? Do you declare ALL of the variables used in your scope at the top of your function? No? Why? Because it’s tedious, annoying to read and interpret? Well, you’ve just used a Bad Part ™. JavaScript doesn’t handle this for you, and it really should.

    Don’t stupid unnecessary reserved words bother you in JavaScript? Come on.. half of them aren’t even used: http://javascript.about.com/library/blreserved.htm

    If you can describe your program flow in 1/3 less code, you’ve just saved yourself and your fellow developers uncountable time. I’m not even going to mention the massive amounts of shorthands, expressive array notations, inline string variables, optional parameters, deconstruction assignment, and more. These are the traits of a modern language, in a language that is anything but. There’s so much more to it than simply removing parenthesis and semi-colons, and it’s naive to look at it that way. That was simply a benefit of significant whitespace.

    If significant whitespace is an issue to you, then an argument here is futile. Your project should already abide by whitespace guidelines, and thus this requirement is non-intrusive. Python had it right. CoffeeScript takes it a step further, allowing optional newlines in some cases.

    You really can’t argue it until you overview each topic (these are real, applicable solutions to the Bad Parts ™ of JS). http://jashkenas.github.com/coffee-script/#top

    There is no extra step in compilation. It is in no way inhibiting. Simply use compile-on-save in editor, or –watch parameter: coffee -wc -o src src (watches and auto-compiles /src dir). There’s no run-time overhead. Also, use Less.app, not Less.js. :) Simple solutions are simple.

    The major downside is matching up lines for debugging. But really, that’s a problem with CoffeeScript not being natively adopted, ..haha.. :-P Personally, I’ll take the trade-off. I’m confident in my ability to understand both “languages.”

    Preprocessing also opens up the possibility for third-party developers to extend the language in interesting ways. Although, the defer keyword was denied: http://gfxmonk.net/2010/07/04/defer-taming-asynchronous-javascript-with-coffeescript.html Coding sequentially for game logic is better IMHO (something like StratifiedJS), as nested event handling (prevalent in Node.js) can add an unnecessary layer of complexity. It’s good people are taking the language into their own hands and improving it, because standards bodies have a hard time getting anything done (ECMAScript 4). ;)

  • Shadow Skill

    There is really no such thing as “self-explanatory” code the explanation just comes from elsewhere. You claim that my project should already be following whitespace conventions, why is that? What law dictates that this should be the case? Why introduce a downside that is even worse than the one that existed in the language that this language actually compiles to? What is the point of people even adopting this if you have to deal with bugs caused by distortions of the formating? To give a similar example from a different field public buildings in the U.S. tend not to have doors that open inward if the mechanism to open the door must be triggered manually (I.E. A pull versus a push mechanism.) and the space is high traffic.

    The reason for the use of push doors has to do with how a pull door has to be opened, the user has to pull the door towards themselves and step back to allow the door to open. See the problem yet? No? The problem occurs when you have an emergency and people panic. A pull mechanism creates a death trap if all the people try to rush the door. If a hundred people are pressing up against the closest person to the door that person isn’t going to be able to open the door. Push mechanisms do not have that problem because the first person to the door will be able to open it regardless of how many people are behind them trying to make it to the exit.

    Suddenly a supposedly minor consideration has become a rather important usability feature as far as the architect is concerned. The same is true for language designers since they have to deal with human cognition. It’s naive to think that syntax doesn’t matter for a language whose sole purpose is to shield users from another language since that has an impact on usability.

    This isn’t about syntactical differences. This is about safe and self-explanatory code. This is about the Good Stuff ™. Have you not seen Crockford’s criticisms? They are entirely valid, IMHO, but JSLint is no great solution either. I know the problems with JavaScript, and when I see how CoffeeScript is deconstructed, it makes perfect sense.

    How is it that you claim that this is not about syntactical differences yet you say something like this in the next breath

    If you can describe your program flow in 1/3 less code, you’ve just saved yourself and your fellow developers uncountable time. I’m not even going to mention the massive amounts of shorthands, expressive array notations, inline string variables, optional parameters, deconstruction assignment, and more. These are the traits of a modern language, in a language that is anything but. There’s so much more to it than simply removing parenthesis and semi-colons, and it’s naive to look at it that way. That was simply a benefit of significant whitespace.

    which has everything to do with syntactical differences?

    Coffeescript has to be as powerful as Javascript to serve its intended purpose, the functionality must be representable in Javascript. The syntax really is the whole point because of Coffeescript’s intended use. It doesn’t replace Javascript, it shields the user from the syntax of Javascript in the same way that ActiveRecord, DataMapper, and Sequel shield Ruby programmers from the syntax of SQL. That is why I said that Coffeescript should have been more like Linq or the other ORM’s I mentioned in my last sentence. Coffeescript’s purpose is more in line with those DSLs than it is with Jruby,Clojure, or IronPython. Even if you did have native support for Coffeescript in web browsers the choice of syntactic indentation would limit, if not preclude embedding Coffeescript inside HTML if said HTML was stripped of all whitespace to save bandwidth.

    Of course you could set things up so that if coffee is in the script type attribute it is passed over by the space stripping tool, but now you are doing contortions to support an unjustifiable design choice that is the result of the designer not considering the consequences of that choice more thoroughly.

  • Eric

    Read the complaints above about “learning a new language just to make semi-colons optional? no thanks”, whitespace, and such. (Likely without reading the specifications). That is what I mean by syntactical differences. You’re really stretching it if you can read the CoffeeScript homepage and call those merely syntax. It’s syntax carries different (more compact) functionality all together. Sigh; not worth responding. I’ll go do something more productive with my time, like write one line of code that does what 10 of your JavaScript does, without the possibility of, oh, I don’t know, the many many bugs CF can prevent in common (high level) logic code.

  • shadow skill

    Next you will claim that ActiveRecord is more powerful than tsql even though ActiveRecord generates SQL code. Did you even read what I said? My entire point has been and is that creating a new and sadly worse syntax for Javascript as a separate language is of little benefit when compared with the possibility of eliminating the change of context that we all have to go through by providing a means to create Javascript from the general purpose languages we use to create dynamic websites! We should not even be writing Javascript/Coffeescript, we should be writing Ruby, C# or whatever the hell else we already use on the server. Me learning Coffeescript does not solve the problem of having to learn a third language just to do the U.I. of a single application. Coffeescript already has a fork with a slightly different syntax. (I believe mainline coffeescript backports some of this fork’s changes.)Just because you can write something on one line as opposed to ten does not make that form necessarily better.

    I prefer to use the lambda syntax when working with Linq mainly because it is fairly Ruby like and Ruby is how I learned about lambdas and block scope in general. However I recognize the fact that the more wordy SQL like syntax is probably more readable and therefore better than the initially more cryptic but shorter lambda syntax that I use. This is not surprising since the syntax of SQL was designed so that people who were not programmers by education or training could be fairly effective with a database of the relational variety with a minimum of training.

    CoffeeScript needed to be this:http://projects.nikhilk.net/ScriptSharp/ Sadly this project doesn’t seem to support the things I need to use, but this project has the right idea.

    This one is also something on the right track:http://jsc.sourceforge.net/

  • Abdulquadri

    Men… Programming has become Religion! lol

  • David

    1. If you like Ruby you’ll like CS, probably for the same reasons you like Ruby. And vice versa if you detest Ruby.
    2. It’s not a replacement for learning JS.
    3. It encourages writing good JS by making it easier (less tedious).
    4. If your main use of JS is to add a few jquery behaviors to a page here and there, don’t bother with CS.
    5. If you’re writing a rich client app or node.js, CS will easily help keep it from turning into a spaghetti bowl. It makes the meaning of your code easier to see by abstracting away so much of the decoration. I didn’t realize how true this was until porting an app from JS to CS.
    6. It isn’t a replacement for jquery or underscore. Makes those easier to use, however, but getting the parens and curly braces out of the way.
    7. Yes there is the extra step when debugging of corresponding the JS error to your code. If your eyes are sharp enough to wade through all those curly braces, you’ll do fine.

    If you like curly braces and you want a language that compiles to JS or PHP at will, check out Haxe.

    • http://www.robertglynn.info Robert M Glynn

      Just wanted to thank David for his comment (April 19, 2011 at 9:22 pm). Helped me make a decision I had been mulling over for a while.

  • http://allenchan.org Allen

    What if you guys provide a video tutorial, the CoffeeScript is new to us in my point of view.

    But also thanks for the long article.

  • Ganesh Prasad

    I would have put “JSLint approved” at the top of the list of Yays :-).

    Nice article, thanks.

  • LoTan

    CoffeeScript, to me, seems like a compliment to JavaScript as opposed to a replacement of it. It also feels like something that is a personal preference. If you’re writing any fair amount of OO based JavaScript, the use and love of CS is about in line with why people love jQuery and the foundation that turned jQuery into what it is today – you can do more, and write less( and it’s cross browser!). I know JavaScript extremely well in terms of prototyping for class models, contexts, closures, memory leaks, and I have familiarity with ExtJS/Sencha, jQuery, Prototype, Draw2D, BackboneJS, and others and have no issues with CS. This belief that only those who don’t know JavaScript would like CS, or using CS keeps you from having to learn JavaScript, is just a fallacy and a bad idea. You guys appear slightly stubborn or purist, from what I can see, and were biased against CS as soon as you read that it’s complied/translated to JavaScript and that sounds like a huge no-no to you.

    One could argue that it may be hard to debug, but I’ve read the generated code and there is nothing complex about it, so you may find yourself stepping through the generated form of the code to fix an issue, and it will not completely hide JavaScript from you, but I don’t think it should or that it’s that big of a problem. As for the line numbers not matching up, that could get aggravating, so point noted.

  • http://pixelturf.com suhail

    good introduction to coffeescript. neat and simple. good one.

  • http://www.riptide7.com Stan

    I tend to agree with Jeremy Carlson. I just don’t seen the point in learning yet another ‘shortening’ method of javascript. I just learned of coffeescript the other day at an interview. The guy asked if I knew it. I didn’t and that could be one of the reasons I didn’t get the job. So I started looking into it. Frankly, it seems to be a pain in the a$$. I still haven’t figured out how to fully implement and actually use it. I’ve got node.js, npm, node this, node that, but I’ve yet to figure out how it’s supposed to tie into the browser and my sites.

    I’m sure I’ll get it eventually, but what’s the point? All the countless hours spent learning yet another shortening language, could be spent getting better at jQuery, a language that is already accepted and widely in use. Why should I bother with this one?

    I haven’t found one compelling answer to that question. It just seems that yet another developer got cute with JavaScript further complicating our lives, because it’s yet another thing employers will want you to know. And that is the problem, employers couldn’t tell you why they want this stuff, but it’s out there, so they expect you to know it. So here’s my answer to CoffeeScript, the guy who wrote it, and those like him, STOP! Enough is enough. Don’t make our lives more tedious by adding more abstractions. jQuery works great and is short enough. I’m used to JavaScript and this is confusing to me. Sure I can learn it, but why, seeing as I already know the core language? All this does is make it easier for NOOBS to gut in on an already crowded market.

    • Ivan

      This is a scary mindset. If everyone felt this way our industry would accelerate more slowly. Learning a shortening language like this speeds up the development of web applications so more time can be devoted to strategy and A / B testing and less on making sure you have defined your variables in the correct scope.

      If you want to stagnate and rest on the laurels of what you are comfortable with no one is stopping you. But if a prospective client or employer wants someone who can code more efficiently by using modern tools know that you probably are not getting that job.

      • Evan Plaice

        Acceleration isn’t the issue. The real question should be, what value does coffeescript add.

        Here’s what sucks about CS:
        Breaks the ability to use fall-throughs on switch statements (one useful case for using them over if/then/else statements). Requires a pre-processor to be running in the background. Breaks error tracebacks. Requires another lint library for syntax checking. Follows applescript’s written statements. It’s one-way compatible with JS meaning code used to tune the lower-level javascript can’t be propagated back up the chain. Adds yet another level of abstraction. Breaks the ability to declare multi-line object literals (very useful for creating objects that contain function calls as parameters).

        Here’s what’s good:
        Displacing brackets in favor of whitespace (which I personally prefer). Fixes variables to default to local scope. Provides a familiar syntax for newbie devs making the transition from Ruby to JS.

        It provides a ‘comfortable’ path to adopting Javascript for Ruby developers but much of the development world doesn’t like Ruby. Writing OOP code and managing organization isn’t an issue for experienced devs.

        I have avoided adapting CS because cross-platform (windows, linux, and mac) continuous build systems haven’t been available until lately (ex grunt). I’ll give it an honest chance to see if it grows on me but from a strictly semantic POV, CS has little to offer. I have worked with a lot of languages and this just feels like an exploratory stepping stone.

      • http://twitter.com/s5 Steve Simitzis

        I’m currently using CoffeeScript on a large project (one that I originally wrote in JavaScript) as an experiment, and I largely agree with you. I’ll give it a fair shake for a few more months, but to me the whole language seems like a pointless exercise; one that doesn’t provide any benefit over JavaScript. In many cases, it’s a step down. Example: Automatically adding breaks to your switch statement. Perhaps this helps junior programmers who view “break” as a merely decorative keyboard, but this is a useful part of C-based languages and should not be trimmed out.

        Some criticisms, like losing your line numbers in debugging, seem like only a matter of time until that’s sorted out. Significant whitespace over braces is probably a religious dispute. I personally hate it, and find copying and pasting code between files to be a constant debugging nightmare. (“But it *looks* indented properly? So why is that variable not in scope? Oh wait, I copied and pasted from old code / a colleague’s file that used spaces instead of tabs.”)

        I don’t think english words over symbols is any better. “if (chickens && cats)” is a statement I can immediately parse. “if chickens and cats” looks like a blur of words rather than variables and symbols. I’m sure some people prefer that style, but it shouldn’t be thought of as an evolution or an improvement. Merely one set of preferences over another.

        And that is ultimately what I dislike about CoffeeScript. As a language, it’s a downgrade in some areas, an upgrade in others (for/in loops and better scoping are improvements), and a matter of taste for the remaining 90%. But it’s being pushed as so much better. How exactly does it speed up development? By saving me typing the curly braces that nearly all IDEs will automatically complete for me? I spend more time tabbing and retabbing my code than I have ever spent matching curly braces and parens.

  • Ijin

    If you have noticed the changes in available draft of ECMAScript 6 that are available you’ll notice that learning CoffeeScript is just preparing for the future. I found very smart conclusion in this post considering for and against using CoffeeScript.
    http://codefedonarts.com/2013/02/17/why-i-have-given-up-on-javascipt-for-coffeescript/
    Thanks for writing great article.