Coffeescript's existential operator

Love it or hate it, coffeescript does make your front-end javascript code more concise. And one of its great features is existential operator, which helps to remove most of null and undefined checks. Let’s see how it works:

In its basic form, it’s pretty self-explainatory.

if variable?
  # do something
if (typeof variable !== "undefined" && variable !== null) {
  // do something

You can chain these checks for deep object lookup:


But there’s more. Run a function only if it’s defined:

if (typeof === "function") {;

Or lookup an array ony if it’s defined: (this one does not check if property is an array though)[1]
var _ref;
if ((_ref = != null) {

Existential operator can be used in assignment: ?= 'value'
if ( == null) { = 'value';

It only assigns when property is not defined. It’s especially handy for boolean variables - let’s compare this to ||= operator:

# ||= operator
variable = false
variable ||= 'value'
variable # => 'value'

# ?= operator
variable2 = false
variable2 ?= 'value'
variable2 # => false
comments powered by Disqus