And/Or

CoffeeScript style indicates that or is preferred over ||, and and is preferred over &&. I can see why, as the former is somewhat more readable. Nevertheless, the two styles have identical results.

This preference for natural-language style code also applies to using is instead of == and isnt rather than !=:

string = "migrating coconuts"
string == string # true
string is string # true

One extremely nice addition to CoffeeScript is the “or equals”, which is a pattern Rubyists may recognize as ||=:

hash or= {}

If hash evaluates to false, then it’s set to an empty object. It’s important to note here that this expression also recognizes 0, "", and null as false. If that isn’t your intention, you’ll need to use CoffeeScript’s existential operator, which only gets activated if hash is undefined or null:

hash ?= {}

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.