CoffeeScript overview and resource inventory

An overview of CoffeeScript and good learning resources

As I've written about previously (although far from as much as I hoped to), I'm teaching a course at Linnaeus University on Advanced JavaScript for RIA creation. In the course, parallell to creating a RIA, the students are also tasked with doing a deepdive into a related subject of their own choosing (most often on a technology employed in the RIA creation).

Because I'm still working my way to a 3rd year degree myself, I ended up in the weird situation of getting to take my own course! Although not giving myself a grade, unfortunately. I made my deepdive in CoffeeScript, which I thought might also be fit for the Krawaller blog.

So here it is: a repost from my student alter ego, an overview of CoffeeScript:

 

What is CoffeeScript?

Briefly explained, CoffeeScript is a thin syntactical layer on top of JavaScript. You write CoffeeScript, it compiles to JavaScript, which is then run in the browser (or Node, or wherever) in the usual way.

As has been widely realised the last few years, JavaScript is a most excellent language when wielded right, utilizing its expressiveness and applying functional programming.

However, the syntax is far from as elegant as the underlying language. We all know the story of how Brendan Eich, JavaScript's creator, was forced to make it "look like Java". Had he not been wearing that shackle at the time (and not had the very short timespan to work with), JavaScript would have been looking very differently, and there likely would be no need for CoffeeScript.

But this, in essence, is the problem space that CoffeeScript tries to solve: it aims to negate the clunky syntax, exposing the beautiful language beneath. It does this by:

  • ...using significant whitespace. We're already indenting our code, so why should we also have to enclose a function body in curly braces? In CoffeeScript, we can declare objects and function, and use controlstructures such as if or switch, with just whitespace to signify the depth.
  • ...cleaning the syntax. By sacrificing the (unnecessary) ability to have many statements on a single line, we negate the need for semicolons completely. CoffeeScript also strives to be more readable, by changing existing keywords and operators to more succinct and self-explanatory versions. Thus "function" is distilled down to the simple dash rocket "->", equality is "is" instead of "===", etc.
  • ...adding new keywords to simplify commonly occuring patterns. This includes class declaration, prototype access, destructuring assignments, loops, and many more. Users of Ruby or Lisp will recognize much of this. These concepts are a very powerful way of shortening your code, and the reason that CoffeeScript code is almost always half or less of the size of the generated JavaScript.

For actual examples, there is a long list of learning and demonstrating resources in the how section. If you're eager to see it right now, take a quick look at the official homepage.

So, underneath it all, it's the same old JavaScript. One of the creator's, Jeremy Ashkenas, goals was for there to always be a 1 to 1 correspondence with JavaScript and CoffeeScript. This makes it easy for someone already into JavaScript to adopt CoffeeScript and sharpen his game. It also means that your CoffeeScript can be used with any and all JavaScript library, and that you can use all JavaScript libraries in your CoffeeScript. In fact, CoffeeScript and jQuery makes for a very sexy combination, as this article notes.

 

Why (not) use CoffeeScript?

There are two main advantages to CoffeeScript:

  • The code is more readable. This is not a trivial thing - being able to glance through someone's code and deduce what it does is a very commonly occuring task, and CoffeeScript will at times read almost as pseudo code, clearly communicating the intent. 
  • The code is shorter. This, too, will of course contribute to readability. Not just by taxing less patience - the extra lines that you don't have to write in CoffeeScript are commonly rather abstract and thus hard to decipher, such as loop juggling, inheritance gymnastics, etc.
  • A third, inofficial advantage, significant to my proud self, is that you feel smarter when using it. Being able to more with less was always the badge of the ninja, and CoffeeScript opens up even more ways of accomplishing that (and more ways to abuse it, of course...).

Lets now instead touch on the more interesting subject of why not to use it!

  • It requires new tools. This isn't necessarily a big problem, as many of the popular editors out there have plugins for CoffeeScript already. But finding and installing that plugin is a hoop you have to jump through, and if you're not using one of the editors with a plugin available, you have to invest the time to learn a new editor (which you probably should be doing anyway, as you're likely using an editor without a plugin API). 
  • It introduced a new step in the build process, as the code has to be compiled to JavaScript before it is used (at least for now, see the last bullet below). This is pretty trivial once you set it up to autocompile whenever the CoffeeScript file is saved, but that initial setup still has to be done.
  • It is a threshold in any collaboration project, which most projects are. Even though, for an experienced JavaScript programmer, grokking CoffeeScript can be done in a few hours, it is a few hours that every non-CoffeeScript developer has to invest before he or she can contribute to the code. This will have a serious impact on the amount of people ending up actually contributing. 
  • For runtime errors, you'll get linenumbers referencing the generated JavaScript. Mostly you'll immediately know where in the CoffeeScript code the bug is located, but when you don't it is a real drag: you have to open the generated file, find the line, deduce from the context what CoffeeScript function this correlates to, then find that corresponding section in the CoffeeScript file and fix the error. There are projects in the work to mitigate this (CoffeeScript execution is coming to Firefox, and already present in Rails), but at the time of writing it remains a very real problem.

Whether the pros outweigh the cons is of course heavily situational, depending both on the individuals and the project. 

 

Who is CoffeeScript for?

To me, the answer to this question is very short: it is for someone who already knows JavaScript, and preferrably knows it rather well. Two reasons for this:

  1. If you only know CoffeeScript but not JavaScript (although obviously knowledge in one will spill over to the other), you are very limited in finding use for your services.
  2. Someone who is already well versed in JavaScript is also equally familiar with its downsides. He or she will therefore understand the point of CoffeeScript, and be able to use its strengths even better.

If you're looking to get into web development, CoffeeScript (in my humble opinion) is not a good place to start. Learn JavaScript the traditional way, and when you know it well enough to be annoyed by the verbose syntax (and have thought through the pros & cons above), adopt CoffeeScript!

 

How is CoffeeScript used?

The primary resource for learning CoffeeScript is definitely the excellent official homepage, which is a testimony to good web design. Apart from a very accessible documentation it also has an interactive console, where you can type CoffeeScript code, see the generated JavaScript in real time, and execute it to see the result. The code examples in the documentation uses the same functionality, enabling you to toy around with it for easy understanding.

That said, there are several other good resources for learning CoffeeScript. I've done an inventory below, split into various categories depending on their media.

Books

First and foremost we have CoffeeScript - accelerated JavaScript development by Trevor Burnham was my foremost resource when learning the language. It is published by Pragmatic Programmers, available as both paper book and ebook. Normally, when a book is published on something that has just recently been made available (or, as in CoffeeScript's case, reached critical popularity mass), you'd expect a greedy rush-job. This is not the case here, and it is evident that Trevor has lovingly crafted the book over a length of time. The book assumes previous familiarity with JavaScript, and so focuses on CoffeeScript's additions.

One of my favourite JavaScript books for beginners is the free online book Eloquent JavaScript by Marijn Haverbeke (recently also made available in an edited paper version). He made this available to the public domain, which enabled E. Hoigaard to "port" the book to CoffeeScript, resulting in Smooth CoffeeScript. His book retains the charm and razor-sharp teaching skills from its predecessor, successfully translated to CoffeeScript's concepts. Do note, however, that both books also teach basic programming at the same time, so Smooth CoffeeScript is not just a dedicated syntax-learning resource.

The two now mentioned books stand apart in regards to scope and author-spent time, but there are a few more books I'd like to mention. First off we have Little book on CoffeeScript by Alex MacCaw. It is not as meaty as the others, but very succinct and to-the-point. He also employs a very neat function where, for all CoffeScript code examples, you can see the corresponding JavaScript (by clicking the small grey square in the top-right corner). Alex also adopts the neat new trend of housing the book's code at Github, enabling readers to quickly make pull requests to fix errata.

Finally we have the community-driven CoffeeScript Cookbook, also on Github. As the title implies it is not a narrative book as such, but a recipe collection of CoffeeScript snippets. However it is still worth checking out, and I really like the collaboration initiative (although so far, my contribution is limited to removing a few unnecessary invocation parens).

Screencasts

I cannot not have the Peepcode CoffeeScript screencast on top here. It is a commercial product ($12), but well worth the price. Sometimes, with professionally created teaching products, I find that the money is spent more on superficial production values than anything else, but this is not the case here - although it is a very polished product, it is evident that it is also very well though-ought, and that a lot of testing and planning has foregone the recording. Heartily recommended! You'll also learn some Jasmine unit testing at the same time, just for good measures! There are some teasers on their supporting blog post (which is also well worth reading).

There is a really good introduction to CoffeeScript 18-minute video at screencasts.org (who also have a lot of other high-quality web-related content). Extensive transcript is included, which is something I appreciate. The title is apt, meaning it is an introduction and not a full coverage, but as a starting point it serves it's purpose very well, and it does manage to touch on mostly all important concepts.

If you (like many CoffeeScript adopters) come from a Rails background, there is a good 11-minute episode on Railscast about CoffeeScript basics. Rails knowledge is not mandatory, though, as the video focuses on a walkthrough of a conversion of a JavaScript code to CoffeeScript, explaining the concepts in the process. There are some extensive written-out shownotes here. The video gets extra credits from me for the hands-on approach - the teaching while translating concept works really well!

Charles MaxWood at TeachMeToCode has done an episode called CoffeeScript basics, which is a nice, slow-paced walk through how to get started. If you don't want to download the video, it is also available on youtube here. As the other TMTC videos, it is done in a "live" setting where we see Charles hacking away in the editor. The style is not for all, but for someone who is dipping their first toe into the coffee and want to hear the thoughts of someone else doing the same thing, it is spot on.

The same guys later followed up with another CoffeeScript episode called CoffeeScript - the Cool Parts, which is more or less a continuation of the first video. It is done in exactly the same style, but moves on to the more advanced concepts (mainly inheritance). This episode is available on youtube too.

Tutorials

If you prefer to do your learning through more static means, here follows a few articles on CoffeeScript. First out is the Rocking out with CoffeeScript on the net section (well worth exploring) of tutsplus. It is from late 2010, so there are a few things missing (classes). Still, CoffeeScript has been very stable since then, so what's there is all up to date. The article is also very well written - assuming no prior knowledge, it immediately gives you a context, a pro-con discussion, and then delves into the details to be put into that context. Well done.

Stefan Buhrmeister wrote a short but sweet piece on How CoffeeScript makes jQuery more fun than ever. It is a pretty "standard" CoffeeScript quicklook, but also making the point of how integrating JavaScript libraries such as jQuery is no problem. He also manages to highlight how CoffeeScript makes some aspects of jQuery (iterations, callbacks) just plain beautiful. 

ElegantCode has a nice tutorial series by Jan Van Ryswyck titled Exploring CoffeeScript. They start at the very beginning with installing it, and then holds your hand through getting over the initial threshold. Be sure not to miss the later installments, as they are not linked from the first post! 

For a quick overview, there is a neat article on JavaScriptAtoms called CoffeeScript - the other JavaScript. It's not a language primer, but gives you the context and an idea on what CoffeeScript is all about.

Slides

I'm not a fan of digesting slides without the accompanying talk, but I've found a couple that can stand somewhat well on their own legs, if you want a lightning-fast powerpointy CoffeeScript fix. First off we have CoffeeScript the Awesome by James Hughes, which quickly walks through the various syntactic sugars by peppering you with bi-JavaScript-CoffeeScript code examples. James finishes up by offering some tips for using CoffeeScript in a .NET environment.

Jacques Crocker made a really neat in-browser presentation for SeattleJS (navigate using the arrow keys). Again we see the various features demonstrated through code examples, but they are well chosen and crafted, and you very quickly get a feel for the language. Also, the programming behind the presentation itself is pretty impressive.

Twitter

If found it useful to follow the following two Twitter accounts. First off @CoffeeScript, which is the official account. It is run by Trevor Burnham, author of the book. He is really fast at replying, and - needless to say - knows what he is talking about, so this feed is a great resource when you get stumped while coding. Of course, it is also a good way to keep up to date with what's going on in the CoffeeScript world.

Another good resource for that is @CoffeeScript_m8. They are very quick to pick up and tweetlink to new CoffeeScript-related content popping up, and indeed claim that "Follow us, and you won't miss a thing about CoffeeScript!".

Communities

On StackOverflow, putting the CoffeScript tag on your question will quickly give you a slew of answers. Trevor Burnham is pretty active here too, and in general the responses given seem to be of very high quality.

There are also quite a lot of interesting related content on the CoffeeScript section of Quora.com. Unlike StackOverflow this is not a place for help with code matters, but deals more with higher level discussion. Thus you'll find questions like "what are the disadvantages of using coffeescript", "what kinds of programmer are more likely to use coffeescript over javascript", etc.

You'll also find quite a bit of life in the CoffeeScript google group, both troubleshooting and news relays. 

Other resources

As stated initially, the official homepage is the best and quickest way if you just want to try your hand at some CoffeeScript hacking. However, if you're using the excellent JSFiddle, it might be good to know that they have added CoffeeScript support (albeight a bit hidden: open the Panels panel and change JavaScript to CoffeScript in the dropdown). As JSFiddle can persist code this is a good way of sharing CoffeeScript snippets, if you don't want to create a github gist.

The web-based Ace editor (formerly Bespin) also has syntax highlighting for CoffeeScript.

If you're using Firefox and Firebug, you'd do well to check out the Acebug addon. Among other things, it gives you CoffeeScript straight in the console!

There is an excellent CoffeeScript bundle available for the TextMate editor, maintained by mr Ashkenas himself. If you're using TextMate, picking this up is a no-brainer. You get syntax highlighting, a runtime environment, and can quickly inspect the generated JavaScript. For plugins to other editors, see the list in the wiki of the official coffeescript page.

While not a learning resource, the CoffeeKup project (also see readme file here) is well worth checking out; It lets you declare your markup in CoffeeScript! Sounds weird, and it is, but it is surprisingly elegant, and it lets you do content and behaviour with one single language. There has been similar attempts in JavaScript, but due to the verboseness of that language, the result was always even clunkier than html. Now, with CoffeeScript, the idea works!

Posted by David Waller 

0 comments

Leave a comment...