Coffeescript equivalent of Ruby’s ||= (conditional assignment)

Jonathan Ricketson

Ruby has a nice syntax for replacing the value of a variable if the variable is ‘falsy’. It is often used to cache expensive calculations.
it looks like:

def get_expensive_value
  @value ||= do
    # some expensive calculation
  end
end

The equivalent in Coffeescript is:

getExpensiveValue: ->
  @value ?= ( =>
    # some expensive calculation
  )()

This entry was posted on Saturday, May 21st, 2011 at 7:13 pm.