10 good reasons to use CoffeeScript

10 good reasons to use CoffeeScript

Caike Souza talks you through some of the advantages of CoffeeScript and demonstrates why it's worth using the language in your projects

CoffeeScript is a fairly recent language that has been gaining a lot of popularity. CoffeeScript not only leverages JavaScript's powerful object model using a much cleaner syntax, but also adds to its existing features.

In case you are still wondering if CoffeeScript is a language worth learning, I've put together a list of 10 things that drove me to it and have kept me using it for almost all of my projects.

1. Cleaner syntax

Unlike JavaScript, whose syntax is heavily influenced by the C language, CoffeeScript's syntax is inspired by Ruby and Python. If you've ever seen Python or Ruby code, then you should be familiar with some of CoffeeScript's syntax, such as using line endings instead of semicolons to terminate expressions, optional parens for method invocations or conditionals, and whitespace sensitivity, all of which make for a syntax that is much easier to read.

  1. message = 'Hello World'
  2. sayHello message

2. Generates the good parts of JavaScript

It's a known fact that JavaScript has its bad parts. CoffeeScript will always do its best to generate only the good parts of JavaScript. One example is that every JavaScript file generated by CoffeeScript has its own scope. This is done by wrapping the generated code inside an anonymous function, which helps developers prevent naming collisions and unintentionally polluting the global namespace. The generated JavaScript for a simple HelloWorld looks like so:

  1. (function() {
  2.  
  3.   var sayHello;  
  4.  
  5.   sayHello = function(message) {
  6.     return console.log(message);
  7.   };  
  8.  
  9.   sayHello('Hello World');
  10.  
  11. }).call(this);

In the previous example, the sayHello function is only available from inside the anonymous function and it is not added to the global namespace.

3. Fat Arrow

JavaScript is a really powerful and flexible language. Sometimes, however, these features require developers to write extra code to work around them. In CoffeeScript, some of these workarounds are built into the language.

In the following example, we need to access the coffee object's context from inside the callback function. A widely used convention among JavaScript developers is to assign the object's context to a local variable outside the callback function, so that it can be referenced from the callback function, as in the example below:

  1. var coffee = {
  2.   isFull: true,
  3.   watchDrink: function(){
  4.     var that = this;
  5.     $('.drink a').on('click', function(){
  6.       that.isFull = false;
  7.     });
  8.   }
  9. }

If we convert this JavaScript code, including the workaround part, to CoffeeScript, it would still be valid:

  1. coffee =
  2.   isFull: true
  3.   watchDrink: ->
  4.     that = this
  5.     $('.drink a').on 'click', ->
  6.       that.isFull = false

However, CoffeeScript has the fat arrow operator =>, which is a more succinct way to achieve the same goal. The previous CoffeeScript code, now using the fat arrow, would look like so:

  1. coffee =
  2.   isFull: true
  3.   watchDrink: ->
  4.     $('.drink a').on 'click', =>
  5.       @isFull = false

Using the fat arrow, we can now reference coffee's context from inside the callback function via the @ operator. The @ in CoffeeScript is an alternative to the keyword this, however, when used inside =>, it references this from the outer context.

4. String interpolation

CoffeeScript's string interpolation works just like Ruby's. Instead of concatenating string with +, as you would in JavaScript, you can include your CoffeeScript expressions in #{} inside your double-quoted string, like so:

  1. name = 'John Doe'
  2. console.log "Hi, my name is #{name}"

5. List comprehensions

One of the most common ways to iterate over a collection of elements in JavaScript is using the for loop. The code below is an example of a simple for loop in JavaScript:

  1. var names = ['Foo', 'Bar', 'Baz'];
  2.  
  3. for(var i=0; i < names.length; i++){
  4.   console.log(names[i]);
  5. }

CoffeeScript enables you to iterate over a collection using list comprehension, which is a well-known feature from the Python world. The code below is an example of list comprehension in CoffeeScript:

  1. names = ['Foo', 'Bar', 'Baz']
  2. console.log(name) for name in names

Unlike JavaScript for loops, CoffeeScript's list comprehensions are expressions, therefore they can be returned and assigned:

  1. names = ['Foo', 'Bar', 'Baz']
  2. friends = (name for name in names when name != 'Bar')

6. Conditional modifiers

In CoffeeScript you can write conditional expressions: basically a postfix form of conditionals such as if and unless. I find them quite handy for single line expressions. Read the code below out loud and you will see it sounds just like reading a sentence in English:

  1. allowEntrance() unless age < 21
  2. allowEntrance() if age >= 21

7. The class keyword

JavaScript is a prototypal object-oriented language, so it does not have native support for the declaration of classes. CoffeeScript, however, does support classes. Its compiler takes care of all of the necessary translation to proper prototypal JavaScript code for you. A class in CoffeeScript might look like this:

  1. class Coffee  
  2.  
  3.   constructor: (@name) ->  
  4.  
  5.   brew: ->
  6.     console.log 'Brewing'
  7.  
  8.   description: ->
  9.     console.log "Coffee is #{@name}"

The way you create an object from a CoffeeScript class is pretty much the same way you would in JavaScript, by calling the constructor function via the new operator, like so:

  1. frenchCoffee = new Coffee('French')

8. Glimpse of the future

Key people from the JavaScript community, like Brendan Eich, the creator of JavaScript himself, have been advocating for standardising some of CoffeeScript's syntax. Things like prototypal inheritance via the class keyword, the @ operator and => might actually become part of the JavaScript language in a couple of years.

"I advocated strongly for standardising prototypal inheritance a la CoffeeScript’s class, super, and @ syntactic sugar"  
- Brendan Eich, the creator of JavaScript

9. Community acceptance

Starting on version 3.1, Ruby on Rails supports writing CoffeeScript out-of-the-box. Web frameworks for other languages like Python and PHP have third party libraries that help with the compilation process. There's also support for CoffeeScript from various unit testing frameworks, so the community is actively working on embracing the language.

10. Great resources for learning

The official CoffeeScript website offers excellent documentation and examples to get you up and running:

For those who want to dig into the details of how the language was built, the source is very well documented and is also available on the website. There are many online courses, books, ebooks, blog posts and open source projects you can use to learn more about the language. CodeSchool.com has a CoffeeScript course where you can take the first level for free.

So this is the list of things that I find most interesting about CoffeeScript. Hopefully, this will help you make a decision whether CoffeeScript is a language worth learning.

5 comments

Comment: 2

And 1 big disadvantage of Coffeescript:
Learn a second language! Because you need to know how Javascript works and Coffeescript.

Comment: 3

Since you are still working with the javascript object model, I wouldn't say CoffeeScript is a *completely* different language. If you already know JavaScript, you should be able to grasp CoffeeScript's syntax pretty easily. If you don't know JS well, then learning CoffeeScript will not only help you learn more about JS but also make you a better programmer in general.

Comment: 4

I know javascript and heard about Coffeescript recently. Nice article. It seems coffeescript is way powerful than JS.

Comment: 5

@Priyatech I wouldn't say it's more powerful. It just abstracts away a lot of the "fluff" around JavaScript.
You're not going to be able to do something in CoffeeScript that you can't in JavaScript since CoffeeScript simply compiles to JavaScript.
July issue on sale now!

The Week in Web Design

Sign up to our 'Week in Web Design' newsletter!

Hosting Directory
.net digital edition
Treat yourself to our geeky merchandise!
site stat collection