Published on

In the process of maintaining this blog, I was reintroduced with CoffeeScript. I first read about CoffeeScript in 2009 but I never learned it and I soon forgot about its existence.

For the past 2 weeks I have been learning and practicing CoffeeScript and I wrote this article to share my excitement.

If you write JavaScript regularly and do not use CoffeeScript, I implore you to switch to CoffeeScript. I have wasted hours writing and debugging JavaScript which could have been simplified had I just used CoffeeScript.

A syntax centered around brevity

CoffeeScript borrows strict indentation and list comprehensions from Python, optional parenthesis around method calls (there are exceptions to this rule) and implied return statements from Ruby.

These features reduce keystrokes which, of course, reduce development hours.

Encapsulation

When CoffeeScript is compiled, the script is wrapped in a closure thusly:

This scopes the script to within the boundaries of the closure. Proper scoping prevents method overwriting, name collisions and prevents folks from executing the script inside the JavaScript console.

This will ensure that your script will execute as intended without error.

Automatic boilerplate injection

For example, if you use the method indexOf(), you ought to write a routine which creates the method indexOf() in the case that a browser does not define it. I always forgot to do this in JavaScript, and as a result, my JavaScript was fragile.

CoffeeScript takes care of this for you.

This is best shown through example. This straight-forward class:

Is compiled into this monstrosity:

I certainly could not write the JavaScript above without error. But, more importantly, the JavaScript above is difficult to read.

Reduced syntax errrors

Live compilers like JS2coffee allow you to write and validate CoffeeScript in realtime. Use this to find syntax errors.

Makes you look like a master

Users can only see compiled JavaScript. Even a simple, object-oriented script in CoffeeScript (see example above) will become complex JavaScript. This will impress the pants off of other developers who are ignorant to CoffeeScript (i.e. me circa January 2015).