DHH has announced that Rails 3.1 will ship with CoffeeScript as default option for writing JavaScript.

All web apps use JavaScript (if you don’t, I don’t want to know you! ), and most Rails developers who are used to writing clean and pretty ruby code find it cumbersome to write JavaScript with all its curly braces and colons, (well, at least I did). Compared to that, CoffeeScript is wonderfully easy to understand and maintain. Lets hear it direct from the horse’s mouth –

  • CoffeeScript is neat language that provides an alternative syntax for writing JavaScript; the code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.
  • Its integration with existing JavaScript libraries is seamless (like jQuery, Facebook JS SDK, Google API etc)
  • Works wonderfully in browsers that support JavaScript and JavaScript platforms like node.js
  • The code generated by CoffeeScript is syntactically correct and passes through JSLint without warnings.

A lot of writing about coffee. Let’s brew some –

var square;
square = function(x) {
   return x * x;

Equivalent CoffeeScript –

square = (x) -> x * x

It doesn’t need to explicitly declare the variable ‘square’. The function body starts after ‘->’. We don’t need to use semicolons ; to terminate expressions. And we don’t need an explicit return statement, the last expression evaluated is returned.

How easy that makes a developer’s life! Understandably, Coffeescript has found acceptance in a lot of big rails projects. It is used by Github, 37 signals and more..

Getting Started

  * Lets get it working first – Check out the installation
  * The command-line version of coffee is available as a Node.js utility. The core compiler however, does not depend on Node, and can be run in any JavaScript environment, or in the browser.
  * Check out – the TextMate bundle for CoffeeScript

Why Ruby/Rails devs would love it or The similarity with familiar Ruby/Rails syntax

Variable declaration and expressions
You don’t need to use semicolons ; to terminate expressions, ending the line will do just as well, (although semicolons can still be used to fit multiple expressions onto a single line.) Also, no explicit variable declaration needed. Example –

company = "vinsol"

Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. The empty function looks like this: -> .CoffeeScript uses significant whitespace to delimit blocks of code – very haml-like. Last evaluated expression is returned (no need explicitly ‘return’ values). Almost everything can be wrapped in an anonymous function and used as an expression. Example –

square = (x) ->
   x * x

Default Arguments for functions
Functions may also have default values for arguments. We can override the default value by passing a non-null argument. You also have ruby-style string interpolation. Double-quoted strings can have interpolated values, using #{ … }

about_me = (profession = "developer") ->
    alert "I'm a #{profession}"

Function Calling
You don’t need to use parentheses to call a function if you’re passing arguments. The function call would wrap till the end of line for arguments.

console.log square 2 #=> console.log(square(2)) 

Significant Indendation
Instead of using curly braces { } to surround blocks of code in functions, if- statements, switch, and try/catch, use indentation.

if  x == 2
   alert "Value is 2!"
   alert "Value is not 2!"

We can loop over arrays, ranges, hashes and objects using for operator in the postfix.

alert "I'm a #{profession}" for profession in ['developer', 'designer', 'tester']

Other goodies

Single line conditionals
It provides you with Post fix if-else conditionals. It compiles to ternary operator when possible and closure wrapping otherwise.

status = if couple then 'married' else 'single'
options or= defaults

Class inheritance using extends keyword
CoffeeScript gives a basic class structure,very much like ruby. It lets you add super class, assign prototype-properties and write the constructor.
Constructor functions begin with the name ‘constructor’. You are provided with concise constructors. Rather than doing this.length = length for class constructors, you can simply use the @ shorthand for this, (@length, @breadth) -> with an empty method body would form our constructor.

class Rectangle
  constructor: (@length, @breadth) ->

  area: ->
    alert "Area = " + (@length * @breadth)

class Square extends Rectangle

figure1 = new Rectangle 1,2
figure2 = new Square 1,1


Variable number of arguments get passed as an array in the last argument with ‘…’. Splats are used both for function definition as well as invocation.

gold = silver = rest = "unknown"

awardMedals = (first, second, others...) ->
  gold   = first
  silver = second
  rest   = others

contenders = [
  "Michael Phelps"
  "Liu Xiang"
  "Yao Ming"
  "Allyson Felix"
awardMedals contenders...
alert "Gold: " + gold
alert "Silver: " + silver
alert "The Field: " + rest

You can use single-quotes (otherwise – triple-quotes) for multi-line strings, leading indentation common to all lines will be stripped. Example –

 sample  = 'Lorem ipsum -
 lorem ipsum.. '

Literals in coffeescript for objects and arrays.
When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to YAML.

 matrix = [
en =
    company: "Vinsol"
    location: "Delhi"

Next Post will cover CoffeeScript in Rails 3 and Rails 3.1

Share this:

Privacy Preference Center