Cleanest way to close over a counter in CoffeeScript I haven't spent too much time with CoffeeScript and am trying to have a simple counter:

casper.on('step.complete', ( -&gt;
        i = 0
        return (step) -&gt;
            i += 1
            @echo "Step#{ i }"
    )())


Which works fine but seems to have a bit too many parenthesis for CoffeeScript.
You could do this:

casper.on 'step.complete', do -&gt; # invoked right away
  i = 0
  -&gt; @echo "Step#{ ++i }" # implicitly returned function


Parentheses: None :-)

The do keyword is the equivalent of (-&gt; ...)(), i.e. it means "invoke the  following function immediately" (it's also useful to avoid closure pitfalls in loops, by the way.)

The ++i will increment i before it's echo'ed, and CoffeeScript has implicit return, so the return keyword can be skipped.

Lastly, I left out the step function argument, as you're not using it for anything; you're always adding 1. You can always add it back in of course