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
  )()

Leave a Reply