Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

4/07/2013

How coffeescript makes life easier

There are really awesome people in JS world. One of them is Jeremy Ashkenas - creator of Backbone.js - great frontend mv* framework; Underscore.js - utility library that makes functional programming possible in js  and Coffeescript - small language that compiles directly to js.

Coffeescript is basically a dialect of js which adds a syntactic sugar to language. As we know javascript suffers from his bad parts http://www.youtube.com/watch?v=hQVTIJBZook, which made this expressive language unpopular to traditional programmers - especially those who are educated in classical OO way. That includes global variables, prototype inheritance, that keyword...

Coffeescript tends to bridge that gap, and liberate expressive power of JS by eliminating it's bad parts. In my opinion, it completely succeeded. It is best to write some code, in order to understand.

First, variable. No need for var keyword anymore:

var a = "Hello"
// becomes
a = "Hello


Next, function keyword. Function is one of the most used keyword in js, so it can become hard to type it over and over again. In coffeescript , there is fo function keyword. You just have to do this:

function fn(){
    // some code
}

// becomes
fn = () ->

// and if there is no arguments

fn = ->


Prototype keyword is also avoided:

// instead

Fn.prototype...

// now we use

Fn::some_prop

Objects are simplified:

// No curly braces around object properties:
myObject =
    prop: "some_prop" // needs proper usage of indentation

Boolean
// true becomes yes:
a = yes

// false becomes no:
b = no

No parentheses:
// in most cases there is no parentheses
console.log "Hello Coffee"

In coffee, statements are expressions, so you can write:

console.log if is true // expression is value

There is much more to discover. Writing code in coffee is like driving a new car after old cluncer. So take a next step in your developer life, and start to compile coffeescript, that's fits perfectly with node and backbone ( coincidence ? )

Happy Coding.

No comments:

Post a Comment