Coffeescript --- How to create a self-initiating anonymous function?

user537339 picture user537339 · Apr 9, 2011 · Viewed 20k times · Source

How to write this in coffeescript?

f = (function(){
   // something
})();

Thanks for any tips :)

Answer

Trevor Burnham picture Trevor Burnham · Apr 9, 2011

While you can just use parentheses (e.g. (-> foo)(), you can avoid them by using the do keyword:

do f = -> console.log 'this runs right away'

The most common use of do is capturing variables in a loop. For instance,

for x in [1..3]
  do (x) ->
    setTimeout (-> console.log x), 1

Without the do, you'd just be printing the value of x after the loop 3 times.