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
Written by Robert May
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#