Mmmm Coffee…Script

Is CoffeeScript the way go?

A while back, I wrote about comparing Haml to ERB, expressing an interest in the apparent simplicity brought by Haml and a desire to dive deeper into it. Well, sadly, that hasn’t happened yet, and I’m not sure if it will . Now that I am neck-deep in JavaScript, I’m faced with a similar comparison: JavaScript or CoffeeScript? This time, the readability and simplicity offered by CoffeeScript is MUCH more enticing than my previous comparison.

Let’s make some coffee

So what is CoffeeScript, anyway? While I was studying Rails via the Flatiron School online program (Learn), I noticed these .coffee files time and time again as I explored the many files that Rails generators, well, generate. It wasn’t until I dived into the JavaScript section that I had a light bulb moment.

Aha! It all makes sense now!

CoffeeScript is a language that compiles into JavaScript. It’s a one-to-one conversions, so you don’t have to worry about losing any functionality. It takes elements from Ruby and Python to make your code more readable and simple with the addition of more whitespace. Case in point…semicolon ( ; ), parenthesis ( () ), and curly bracket ( {} ) usage is significantly reduced, and in many cases even eliminated. Better yet, CoffeeScript gives you command line controls to convert a .coffee file into a .js file, and even to keep that .js file updated whenever the .coffee file is updated.

And the crowd goes wild!

Will I have the same reaction as I did with Haml? I think not. Why, do you ask? The fact that Rails defaults to CoffeeScript when you run a generator makes me inclined to think that it’s the future/best practice. I don’t know about you, but that’s a pretty big and logical reason for me to venture down the CoffeeScript path.

or in this case, what does it do?

How do you take your coffee?

This is all well and good, but how does CoffeeScript look…how does it feel? To start, when you declare a function in CoffeeScript, it will also be the equivalent of a regular old JavaScript function expression:

// JavaScript
var person = function() {
return "Hello there!";
}
// CoffeeScript
person = -> 
'Hello there!'

You can see how in CoffeeScript, you don’t even declare the variable. Rather, it’s implicitly understood. Also, no messy parentheses, semicolons, or curly brackets (as I said before), and also no need to even use the word function, replaced with ->. The result, in my opinion is something much more readable, logical, and easy.

Ah, now that’s a good cup o’ Joe!

Now, as was the case with Haml, I have only had but a “taste” of CoffeeScript, but what I have seen really excites me. As I begin the next section of my curriculum (Rails and JavaScript), it’s my goal to study up on CoffeeScript as much as I can — even by making .coffee files for every .js file if that’s what it takes! Even so, I look forward to it!