jwzppw
Last Updated: February 25, 2016
·
5.645K
· robotmay

The Existential Operator in CoffeeScript

I often see people writing CoffeeScript without using the existential operator (a question mark), probably because a lot of its interesting uses aren't mentioned in many places except the great Little Book on CoffeeScript.

At its most basic, as explained in the book, it returns true unless the variable is null or undefined:

eatFood() if food?

It can be used similarly to the .try(:method) in Rails, as in this example which you may have seen in some tutorials:

# Only call .log if console exists
console?.log "Example"

One of my favourite little tricks lately has been doing the following for handling callbacks:

example = (data, callback = null) ->
  someValue = anAsyncThing(data)
  # Only execute callback if it isn't null
  callback?(someValue)

example (value) ->
  console?.log value