HOOKED ON COFFEE

More and more I find myself talking about CoffeeScript and all the things I like about the language so I thought it would be a great idea to summarize all my talking in a post. Before I begin I must say that one of the best things about CoffeeScript is that it has given me a greater understanding for JavaScript.

Me and JavaScript

I have always had a love/hate relationship with JavaScript. Actually, JavaScript were one of the first languages I wrote code in and JavaScript gave me the inspiration to keep coding and learning new languages. Since then the JavaScript community has really exploded with all kinds of cool libraries and frameworks and I think we will see more and more around Node.js like Meteor… but JavaScript is not a smooth language to work with in my opinion. It could be quite nice after adding some libraries to your codebase but I find native JavaScript quite poor and missing a lot of language features. Don’t get me wrong JavaScript has a nice object model and some good parts but I don’t think JavaScript is exposing them as well as CoffeeScript does.

Why I like CoffeScript

CoffeeScript is a language that compiles into JavaScript. Everything that is possible in CoffeeScript is possible to achieve with native JavaScript but I promise you that it’s a lot of extra effort. Relax, I will not write about every language feature, you can find that type of reference documentation here. I will show some cool things that I hope will convert you to a CoffeeScript lover!

Prototypes… classes?

I have seen a lot of examples of prototyping and libraries for simulating classes in JavaScript, some of them are really nice but which one to choose and should you really need to add a library to get support for classes? Some of you might say “Yeah, yeah… JavaScript is very object oriented without classes and we don’t need them”, that is maybe true… but why do we have all of those libraries that simulates classes?… it seems that at least a part of the JavaScript community wants classes.

Okay, so a JavaScript function is a object, functions can then be used to simulate classes and we can use prototypes to extend that function-object. Prototyping in JavaScript is quite hard to get right and you need to decide which approach to use. CoffeeScript makes that decision for you and implements it quite well through the keyword class(!)

CoffeScript to the left, JavaScript to the right.

Prototyping is even harder if you want one JavaScript object to inherit from another. CoffeeScript does that through the keyword "extends".

class Person  
    constructor: (@firstName, @lastName) ->

    getName: ->
        @firstName + " " + @lastName

class Developer extends Person  
    constructor: (first, last) ->
        super first, last

anton = new Developer "Anton", "Kallenberg"  
console.log(do anton.getName)  

CoffeeScript also has a shortcut for extending the prototype of an existing object, using the "::"-operator

Note that I compare with != in CoffeScript but it translates to !== in JavaScript. CoffeeScript does not have “loose type comparison” to avoid unexpected results of type coercion.

Scoping

You may noticed that I prefixed my argument variables with @ in the previous example of the Person class. @ is a shorthand for “this”. Also by adding the @ to the method arguments I tell the CoffeeScript compiler to create backing fields for the arguments and to make them private.

The fat arrow (=>) is another way that CoffeeScript handles scoping. The fat arrow binds “this” to the current instance of the class for the function defined.

The fat arrow can for example be useful when calling a callback in a different scope of "this" and want "this" to be the class instance, for example when using jQuerys click event

The existential operator

If you are not convinced yet that CoffeeScript rocks the existential operator maybe makes it more interesting. Lets say you want to check the property containing work description of some employees objects but you are not sure if the employee object is null or the name of the property containing the work description. In JavaScript this would look something like this:

// ...Don't even bother...

Well, it would be quite a lot of code, in CoffeeScript that could be written with the existential operator ("?").

developer = cto = hr = null  
developer = {desc : "coding 4 food!"}

employee = projectManager ? cto ? developer ? hr ? {desc: "doing nothing" }

workDescription = employee?.desc ? employee?.description ? employee?.workDescription ? "no description found"  
console.log(workDescription)  

First we define some variables to play with; developer, cto, hr and setting them all to null then we create a object for the developer variable. Next we want to set the employee variable to the one of the variables that are not null, if all of them are null we create a new object: {desc: “doing nothing” }. Next we set workDescription to either desc, description, or workDescription if the employee variable is not null. If employee is null or no property is set we set workDescription to “no description found”.

Tools and installation

More on installation can be found at http://coffeescript.org/#installation
The Chrome extension, CoffeeConsole is nice for trying CoffeeScript, it compiles CoffeeScript to JavaScript as you type.

For all visual studio users I can recommend Mindscape Web Workbench.

Sublime text can be extended with a open source plugin to support syntax highlighting and compiling.

If you are interested in compiling CoffeeScript in a ASP.NET web project you can read more about that in my previous post.

Books

If you still reading you probably think that CoffeeScript is worth learning and trying out. I can recommend the books, CoffeeScript: Accelerated JavaScript Development and Testing with CoffeeScript

Thanks for reading!

comments powered by Disqus