CoffeeScript, When to use fat arrow (=>) over arrow (->) and vice versa

No, that’s not the rule I would use.

The major use-case I’ve found for the fat-arrow in defining methods is when you want to use a method as a callback and that method references instance fields:

class A
  constructor: (@msg) ->
  thin: -> alert @msg
  fat:  => alert @msg

x = new A("yo")
x.thin() #alerts "yo"
x.fat()  #alerts "yo"

fn = (callback) -> callback()

fn(x.thin) #alerts "undefined"
fn(x.fat)  #alerts "yo"
fn(-> x.thin()) #alerts "yo"

As you see, you may run into problems passing a reference to an instance’s method as a callback if you don’t use the fat-arrow. This is because the fat-arrow binds the instance of the object to this whereas the thin-arrow doesn’t, so thin-arrow methods called as callbacks as above can’t access the instance’s fields like @msg or call other instance methods. The last line there is a workaround for cases where the thin-arrow has been used.

Leave a Comment