Why CoffeeScript?

Exclusive offer: get 50% off this eBook here
CoffeeScript Programming with jQuery, Rails, and Node.js

CoffeeScript Programming with jQuery, Rails, and Node.js — Save 50%

Learn CoffeeScript programming with the three most popular web technologies around with this book and ebook.

$14.99    $7.50
by Michael Erasmus | January 2013 | Open Source

In this article by Michael Erasmus, author of CoffeeScript Programming with jQuery, Rails, and Node.js, we will look at CoffeeScript from JavaScript's perspective.

(For more resources related to this topic, see here.)

CoffeeScript

CoffeeScript compiles to JavaScript and follows its idioms closely. It's quite possible to rewrite any CoffeeScript code in Javascript and it won't look drastically different. So why would you want to use CoffeeScript?

As an experienced JavaScript programmer, you might think that learning a completely new language is simply not worth the time and effort.

But ultimately, code is for programmers. The compiler doesn't care how the code looks or how clear its meaning is; either it will run or it won't. We aim to write expressive code as programmers so that we can read, reference, understand, modify, and rewrite it.

If the code is too complex or filled with needless ceremony, it will be harder to understand and maintain. CoffeeScript gives us an advantage to clarify our ideas and write more readable code.

It's a misconception to think that CoffeeScript is very different from JavaScript. There might be some drastic syntax differences here and there, but in essence, CoffeeScript was designed to polish the rough edges of JavaScript to reveal the beautiful language hidden beneath. It steers programmers towards JavaScript's so-called "good parts" and holds strong opinions of what constitutes good JavaScript.

One of the mantras of the CoffeeScript community is: "It's just JavaScript", and I have also found that the best way to truly comprehend the language is to look at how it generates its output, which is actually quite readable and understandable code.

Throughout this article, we'll highlight some of the differences between the two languages, often focusing on the things in JavaScript that CoffeeScript tries to improve.

In this way, I would not only like to give you an overview of the major features of the language, but also prepare you to be able to debug your CoffeeScript from its generated code once you start using it more often, as well as being able to convert existing JavaScript.

Let's start with some of the things CoffeeScript fixes in JavaScript.

CoffeeScript syntax

One of the great things about CoffeeScript is that you tend to write much shorter and more succinct programs than you normally would in JavaScript. Some of this is because of the powerful features added to the language, but it also makes a few tweaks to the general syntax of JavaScript to transform it to something quite elegant. It does away with all the semicolons, braces, and other cruft that usually contributes to a lot of the "line noise" in JavaScript.

To illustrate this, let's look at an example. On the left-hand side of the following table is CoffeeScript; on the right-hand side is the generated JavaScript:

CoffeeScript

JavaScript

fibonacci = (n) ->

return 0 if n == 0

return 1 if n == 1

(fibonacci n-1) +

(fibonacci n-2)

alert fibonacci 10

var fibonacci;

fibonacci = function(n) {

if (n === 0) {

return 0;

}

if (n === 1) {

return 1;

}

return (fibonacci(n - 1))

+ (fibonacci(n - 2));

};

alert(fibonacci(10));

To run the code examples in this article, you can use the great Try CoffeeScript online tool, at http://coffeescript.org. It allows you to type in CoffeeScript code, which will then display the equivalent JavaScript in a side pane. You can also run the code right from the browser (by clicking the Run button in the upper-left corner).

At first, the two languages might appear to be quite drastically different, but hopefully as we go through the differences, you'll see that it's all still JavaScript with some small tweaks and a lot of nice syntactical sugar.

Semicolons and braces

As you might have noticed, CoffeeScript does away with all the trailing semicolons at the end of a line. You can still use a semicolon if you want to put two expressions on a single line. It also does away with enclosing braces (also known as curly brackets) for code blocks such as if statements, switch, and the try..catch block.

Whitespace

You might be wondering how the parser figures out where your code blocks start and end. The CoffeeScript compiler does this by using syntactical whitespace. This means that indentation is used for delimited code blocks instead of braces.

This is perhaps one of the most controversial features of the language. If you think about it, in almost all languages, programmers tend to already use indentation of code blocks to improve readability, so why not make it part of the syntax? This is not a new concept, and was mostly borrowed from Python. If you have any experience with significant whitespace language, you will not have any trouble with CoffeeScript indentation.

If you don't, it might take some getting used to, but it makes for code that is wonderfully readable and easy to scan, while shaving off quite a few keystrokes. I'm willing to bet that if you do take the time to get over some initial reservations you might have, you might just grow to love block indentation.

Blocks can be indented with tabs or spaces, but be careful about being consistent using one or the other, or CoffeeScript will not be able to parse your code correctly.

Parenthesis

You'll see that the clause of the if statement does not need be enclosed within parentheses. The same goes for the alert function; you'll see that the single string parameter follows the function call without parentheses as well. In CoffeeScript, parentheses are optional in function calls with parameters, clauses for if..else statements, as well as while loops.

Although functions with arguments do not need parentheses, it is still a good idea to use them in cases where ambiguity might exist. The CoffeeScript community has come up with a nice idiom: wrapping the whole function call in parenthesis. The use of the alert function in CoffeeScript is shown in the following table:

CoffeeScript

JavaScript

alert square 2 * 2.5 + 1

alert(square(2 * 2.5 + 1));

alert (square 2 * 2.5) + 1

alert((square(2 * 2.5)) + 1);

Functions are first class objects in JavaScript. This means that when you refer to a function without parentheses, it will return the function itself, as a value. Thus, in CoffeeScript you still need to add parentheses when calling a function with no arguments.

By making these few tweaks to the syntax of JavaScript, CoffeeScript arguably already improves the readability and succinctness of your code by a big factor, and also saves you quite a lot of keystrokes.

But it has a few other tricks up its sleeve. Most programmers who have written a fair amount of JavaScript would probably agree that one of the phrases that gets typed the most frequently would have to be the function definition function(){}. Functions are really at the heart of JavaScript, yet not without its many warts.

CoffeeScript has great function syntax

The fact that you can treat functions as first class objects as well as being able to create anonymous functions is one of JavaScript's most powerful features. However, the syntax can be very awkward and make the code hard to read (especially if you start nesting functions). But CoffeeScript has a fix for this. Have a look at the following snippets:

CoffeeScript

JavaScript

-> alert 'hi there!'

square = (n) -> n * n

var square;

(function() {

return alert('hi there!');

});

square = function(n) {

return n * n;

};

Here, we are creating two anonymous functions, the first just displays a dialog and the second will return the square of its argument. You've probably noticed the funny -> symbol and might have figured out what it does. Yep, that is how you define a function in CoffeeScript. I have come across a couple of different names for the symbol but the most accepted term seems to be a thin arrow or just an arrow.

Notice that the first function definition has no arguments and thus we can drop the parenthesis. The second function does have a single argument, which is enclosed in parenthesis, which goes in front of the -> symbol. With what we now know, we can formulate a few simple substitution rules to convert JavaScript function declarations to CoffeeScript. They are as follows:

  • Replace the function keyword with ->

  • If the function has no arguments, drop the parenthesis

  • If it has arguments, move the whole argument list with parenthesis in front of the -> symbol

  • Make sure that the function body is properly indented and then drop the enclosing braces

Return isn't required

You might have noted that in both the functions, we left out the return keyword. By default, CoffeeScript will return the last expression in your function. It will try to do this in all the paths of execution. CoffeeScript will try turning any statement (fragment of code that returns nothing) into an expression that returns a value. CoffeeScript programmers will often refer to this feature of the language by saying that everything is an expression.

This means you don't need to type return anymore, but keep in mind that this can, in many cases, alter your code subtly, because of the fact that you will always return something. If you need to return a value from a function before the last statement, you can still use return.

Function arguments

Function arguments can also take an optional default value. In the following code snippet you'll see that the optional value specified is assigned in the body of the generated Javascript:

CoffeeScript

JavaScript

square = (n=1) ->

alert(n * n)

var square;

square = function(n) {

if (n == null) {

n = 1;

}

return alert(n * n);

};

In JavaScript, each function has an array-like structure called arguments with an indexed property for each argument that was passed to the function. You can use arguments to pass in a variable number of parameters to a function. Each parameter will be an element in arguments and thus you don't have to refer to parameters by name.

Although the arguments object acts somewhat like an array, it is in not in fact a "real" array and lacks most of the standard array methods. Often, you'll find that arguments doesn't provide the functionality needed to inspect and manipulate its elements like they are used with an array.

Summary

We saw how it can help you write shorter, cleaner, and more elegant code than you normally would in JavaScript and avoid many of its pitfalls. We came to realize that even though CoffeeScripts' syntax seems to be quite different from JavaScript, it actually maps pretty closely to its generated output.

Resources for Article :


Further resources on this subject:


CoffeeScript Programming with jQuery, Rails, and Node.js Learn CoffeeScript programming with the three most popular web technologies around with this book and ebook.
Published: December 2012
eBook Price: $14.99
Book Price: $29.99
See more
Select your format and quantity:

About the Author :


Michael Erasmus

Michael Erasmus has been developing software for over 10 years. He has been a C# programmer for quite a few of them, but has luckily been enlightened enough to become an open source zealot during the last few years. The most loved tools in his utility belt are Ruby and Rails, Linux, MongoDB, Vim, jQuery, and CoffeeScript.

He's interested in all manner of science and technology, but tends to dwell on things such as elegant and eccentric programming languages, machine learning and statistics, web development, Internet startups, and civic hacking.

He is currently working at 22seven.com, building a service that will help change people's behavior and do more with the money they have.

When he's not sitting in front of the computer, he likes pulling faces to amuse his baby son, apologizing to his wonderful wife for sitting in front of a computer all day, or arguing endlessly with friends, family, colleagues, and random strangers. He lives near the beach in Muizenberg, Cape Town and loves it.

Books From Packt


 jQuery Mobile Web Development Essentials
jQuery Mobile Web Development Essentials

 jQuery Tools UI Library
jQuery Tools UI Library

 JavaScript Testing Beginner's Guide
JavaScript Testing Beginner's Guide

 Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques
Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

 Node Cookbook
Node Cookbook

 HTML5 Boilerplate Web Development
HTML5 Boilerplate Web Development

 Node Web Development
Node Web Development

 Ruby on Rails Enterprise Application Development: Plan, Program, Extend
Ruby on Rails Enterprise Application Development: Plan, Program, Extend


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
v
Z
8
w
Q
D
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software