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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)