about:benjie

Random learnings and other thoughts from an unashamed geek

CoffeeScript: JavaScript, but Clearer

| Comments

I really like CoffeeScript. I really like JavaScript. I’m trying to get into the habit of writing more CoffeeScript since, I think, it allows me to express myself clearer and more concisely, leading to shorter code and (hopefully) less mistakes/bugs. It also makes jumping back into code a month later a much simpler affair since reading the code is so much easier.

The following JavaScript creates a new closure inside each iteration of a loop to store the value of the loop variable i into the closure’s local variable j so that we don’t just console.log(10) 10 times. Though this example is trivial it represents a common method for solving closure related issues in asynchronous code.

JavaScript closure required for correct output
1
2
3
4
5
6
7
8
for (var i = 0; i < 10; i++) {
  (function(){
    var j = i;
    delay(0, function(){
      console.log(j);
    });
  })();
}

The following CoffeeScript does exactly the same thing, you can see the translation line by line from the JavaScript. However once you’ve learnt the syntax you can much more clearly see what is going on with the CoffeeScript than in the verbose and parenthesis-heavy JavaScript above.

.coffee.jsCoffeeScript to do the same thing
1
2
3
4
5
for i in [0..10]
  do ->
    j = i
    delay 0, ->
      console.log j

As a bonus, when CoffeeScript compiles to JavaScript it automatically takes the anonymous function from line 2 and defines it outside the loop so that it need not be interpretted/defined 10 times - it does this optimization for us. (Though I suspect most modern JavaScript engines do this automatically anyway.) To view the compiled JavaScript press the View JavaScript link at the top left of the code snippet.

Note the delay function is just a reordered setTimeout:

.coffee.jsThe delay function
1
delay = (ms, cb) -> setTimeout cb, ms

Comments