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.
1 2 3 4 5 6 7 8 |
|
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.
1 2 3 4 5 |
|
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
: