Coffee with CoffeeScript

Discover why CoffeeScript is a game-changer for JavaScript developers. Learn how this powerful language solves common JS challenges and improves code quality.

10 min read 1,962 words

I am in Bangalore, and the first thing I found here that is classically good is coffee. Obviously I will not be going to talk about coffee here. But about CoffeeScript, which is as good as coffee. I came to know about CoffeeScript from the article written by Scott Hanselman. And I became addicted to it. I am not much of a web guy. I like coding, but mostly on the server end. And Visual Studio is always there to save me. But when it comes to JavaScript, I just crash land every time. I always try to go back to the server as soon as possible. Obviously JQuery is there to bail me out. But still, it is only for DOM. For other things, you have to be an expert. Now, here "expert" means someone who has written JavaScript that passes JSLint with minimum errors. Simple functions and doing some addition is not a big deal, but making a library for a web application is a big deal. At least for me. I am so rigid about my code quality, and JavaScript is a damn flexible scripting language, which can easily become sloppy for me. I always try to follow the architecture defined by JavaScript: The Good Parts. But at the end, following some rules in C Sharp is easier than following them in JavaScript. But God is with me. I found a friend who is damn powerful in JavaScript.

She is the princess of JavaScript. She writes JS like anything. And standards are not violated at all. I don't know how someone can write code like that. She is like Cynthia Rothrock of the web.

Yeah, she is like her only. Just like the photo. A girl you don't want to mess with.

I am not the other person in the picture. It's just FYI.

Like Cynthia Rothrock, she is also a black belt, but in JavaScript. Always kicking around in the web arena. Whenever I get stuck somewhere, she comes, laughs at me, and solves the problem. And what am I in comparison to her? Like the kid shown here.

A white belt kid. Now, what can I do to match standards with her? Technically, I can't. She is a black belt and I am just a kid. But I am a smart kid. I drink some coffee and write CoffeeScript. Yeah, you have a black belt and I have coffee. Now, I come to the point. There is always a need to write good code, whether it is a compiled language or a scripting language.

And good code has two main qualities, as per me. One is its readability, and another is extensibility. If I am writing code, others should be able to read it and also extend it. Now, if you are writing JavaScript like her, others don't find any problem reading or extending it. But otherwise, that will be a problem, specifically with scripting languages. It is prone to get dirty soon.

Here, CoffeeScript has a major advantage. First is its readability, and second is that it is just JavaScript. Here, I am going to use a few examples from the CoffeeScript site only. So if you like to try it out, the site has a try CoffeeScript option. I encourage you to do that.

To try CoffeeScript on a local machine, there are a few options. Nowadays, most IDEs support add-ons for CoffeeScript. But I prefer the Node way. Just install it and start firing commands. You can check out the CoffeeScript home site to get started. I am now starting with an example.

The first thing I love about CoffeeScript is the callback function. It wraps your code around a JavaScript callback function by default. Here is a Hello World example of it. First, let me go with JavaScript:

(function () { 
  alert( "this is CoffeeScript" ); 
}).call( this );

This is a pretty small thing. But I forget it many times. This will call an anonymous function to itself, so it will not mess with other libraries around. And what I wrote in the CoffeeScript file? Just one line:

alert "this is CoffeeScript" 

That's it. That is all I wanted to do. No more functions and all that, no more brackets; nothing. Just like any other DSL—just write what I like to do. It is a pretty basic example, but even from the start, it shows the power of CoffeeScript.

Another thing I like is working with arrays. After having lists and collections in newer languages, working with arrays can be a little bit difficult sometimes. My friend (mentioned above) wrote a complete library to get functionality like List in JavaScript. But it is fun to write arrays in CoffeeScript.

Normally, we do things in JavaScript like this:

(function() {
  var food, foods, _i, _len;

  foods = ['broccoli', 'spinach', 'chocolate'];

  for (_i = 0, _len = foods.length; _i < _len; _i++) {
    food = foods[_i];
    if (food !== 'chocolate') {
      eat(food);
    }
  }

}).call(this); 

But in CoffeeScript:

foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'

It is just pure fun. Here, there are a few things I like to mention specifically. The first thing I have already mentioned is how to do array things in a fun way. Another thing, if you have noticed, is a loop with "_" variables. CoffeeScript takes care of everything, starting from scoping of variables. If you need to mention it at the top or take care that it will not go out of scope, that will be taken care of. Even simple things like loops are written the way they should be written.

Another example for looping:

In JavaScript, it is like this:

(function() {
  var countdown, num;

  countdown = (function() {
    var _i, _results;
    _results = [];
    for (num = _i = 10; _i >= 1; num = --_i) {
      _results.push(num);
    }
    return _results;
  })();

}).call(this);

And in CoffeeScript, it is like a one-liner, giving a forEach loop feeling in JavaScript:

countdown = (num for num in [10..1])

So here is another benefit. If I am insisting on CoffeeScript, it is not against JavaScript, but in favor of learning it. One will know the right way of writing JavaScript. According to the CoffeeScript site, JavaScript generated by it passes JSLint without a single error. So it is good to learn JavaScript using CoffeeScript.

Now, if anyone is a fan of Ruby, it supports Ruby-like syntax in a few cases. Obviously, the web community will like this. You can pass inline variables with "#", and it will work. Let me show you the example.

This time I will go with CoffeeScript first:

yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  "#{child} is #{age}"

And here is the JavaScript for it:

(function() {
  var age, ages, child, yearsOld;

  yearsOld = {
    max: 10,
    ida: 9,
    tim: 11
  };

  ages = (function() {
    var _results;
    _results = [];
    for (child in yearsOld) {
      age = yearsOld[child];
      _results.push("" + child + " is " + age);
    }
    return _results;
  })();

}).call(this);

See how it takes pretty good care of every damn thing. I just fell in love with this. Pushing everything to the top and returning results, changing things with appropriate variables. Everything. Isn't it good???

There are a few more things for conditional operators and looping. But I like to move on to a slightly more complex example. If I want to create a library like JQuery, a few more things must be there. Now, JavaScript doesn't have private or public by default. In JavaScript, functions are the classes themselves. And there is a trick to do private/public things in JavaScript. Most JavaScript programmers must know this. But this is fairly easy in CoffeeScript. It has its own class syntax, and there you go. Code like any other higher-level language. Just check it out.

CoffeeScript code:

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move()

And here is the JavaScript code:

(function() {
  var Animal, Horse, Snake, sam, tom,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  Animal = (function() {
    function Animal(name) {
      this.name = name;
    }

    Animal.prototype.move = function(meters) {
      return alert(this.name + (" moved " + meters + "m."));
    };

    return Animal;
  })();

  Snake = (function(_super) {
    __extends(Snake, _super);

    function Snake() {
      return Snake.__super__.constructor.apply(this, arguments);
    }

    Snake.prototype.move = function() {
      alert("Slithering...");
      return Snake.__super__.move.call(this, 5);
    };

    return Snake;
  })(Animal);

  Horse = (function(_super) {
    __extends(Horse, _super);

    function Horse() {
      return Horse.__super__.constructor.apply(this, arguments);
    }

    Horse.prototype.move = function() {
      alert("Galloping...");
      return Horse.__super__.move.call(this, 45);
    };

    return Horse;
  })(Animal);

  sam = new Snake("Sammy the Python");
  tom = new Horse("Tommy the Palomino");

  sam.move();
  tom.move();

}).call(this);

Isn't it cool? I guess it is. Making a library becomes so easy with this kind of syntax. Obviously, for someone like me who comes from another language background.

Let us see some more complex examples. Function binding. It is easy to bind functions. No extra code at all.

Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart

And it will generate appropriate JavaScript:

(function() {
  var Account;

  Account = function(customer, cart) {
    var _this = this;
    this.customer = customer;
    this.cart = cart;
    return $('.shopping_cart').bind('click', function(event) {
      return _this.customer.purchase(_this.cart);
    });
  };

}).call(this);

See, it is fun. If you are thinking, "What if you are a JQuery fan like me?" Again, I like to repeat a word from CoffeeScript only:

It's just JavaScript

You can use any library with CoffeeScript. Let's check out one of the examples of it.

A CoffeeScript code:

show_message = (msg) -> 
  $('#message').hide().text(msg).fadeIn(2222, -> $('#message').append('!'))

$ -> 
  show_message "world"
  $('#message').click -> show_message "you"

And here we go with JQuery code:

(function() {
  var show_message;

  show_message = function(msg) {
    return $('#message').hide().text(msg).fadeIn(2222, function() {
      return $('#message').append('!');
    });
  };

  $(function() {
    show_message("world");
    return $('#message').click(function() {
      return show_message("you");
    });
  });

}).call(this);

It becomes more powerful when it joins hands with JQuery or other libraries.

Now, for whom is this? This is for people like me. Or even black belts like my friend. It is just fun to write JavaScript. I don't insist on using it, but I surely insist on giving it a try. It is worth investing time in it. Again, if you are a die-hard JavaScript developer, I don't think you need this. But again, there is no loss in learning something new. I am just enjoying CoffeeScript like anything.

So here, there are clearly two options for most developers, including me. Either I can have coffee with JavaScript, doing overtime and solving errors. Or I can use CoffeeScript and have fun time with my (black belt) friend. I prefer the latter. And trust me, this is one of the most fun writing experiences, just like CoffeeScript.

Taste some coffee and have fun. Coding is seriously enjoyable with friends like her and technology like CoffeeScript. Special thanks to Jeremy Ashkenas for giving us CoffeeScript.

Enjoy Coffee!!!

Frequently Asked Questions

What is CoffeeScript and why would a JavaScript developer use it?

CoffeeScript is a language that compiles to JavaScript and helps developers write cleaner, more readable code. It's particularly useful for server-side developers who struggle with JavaScript's flexibility and want to maintain code quality standards similar to compiled languages like C#.

What are the main qualities of good code according to this article?

According to the author, good code has two main qualities: readability and extensibility. Code should be easy for others to understand and modify, which is especially important in scripting languages that are prone to becoming messy and disorganized over time.

How does CoffeeScript help improve code quality compared to regular JavaScript?

CoffeeScript enforces stricter coding standards and promotes better syntax practices, making it easier to follow architectural guidelines like those in JavaScript: The Good Parts. This helps prevent sloppy code and makes it simpler to maintain code quality standards.

Why is JavaScript harder to maintain code quality in than compiled languages?

JavaScript is a highly flexible scripting language that allows multiple ways to accomplish the same task, making it easy for code to become sloppy and disorganized. Following strict architectural standards in JavaScript requires more discipline than in compiled languages like C# where the language itself enforces certain patterns.

Share this article