Available for Hire!


programming tips & tricks

May 5

Implementing an autoincrement counter in CoffeeScript

In one of the recent articles we implemented an autoincrement counter function using closures in JavaScript. Here’s the source code:

var counter = (function() {
  var count = 0;
  return function() {
    return ++count;

Today I was playing around in CoffeeScript, and I basically needed the same functionality. The first idea that came to my mind was this is impossible, CoffeeScript just wasn’t built for this … but then after a little digging in the docs, I found a solution

counter = do ->
  count = 0
  return -> ++count

We could remove the return statement because it is inserted by default to the last line of a function

counter = do ->
  count = 0
  -> ++count

However I like the previous version better, sometimes it is better to be a little more explicit to improve code readability.

Page 1 of 1