óCoffeeScript Cookbook

Create an Object Literal if It Does Not Already Exist

Problem

You want to initialize an object literal, but you do not want to overwrite the object if it already exists.

Solution

Use the Existential operator

window.MY_NAMESPACE ?= {}

Discussion

This is equivalent to the following JavaScript:

if(window.MY_NAMESPACE === null || window.MY_NAMESPACE === undefined) {
  window.MY_NAMESPACE = {};
}

Problem

You want to make a conditonal assignment if it does not exists or if it is falsy (empty, 0, null, false)

Solution

Use the Conditional assignment operator

window.my_variable ||= {}

Discussion

This is equivalent to the following JavaScript:

window.my_variable = window.my_variable || {};

Common JavaScript technique, using conditional assignment to ensure that we have an object that is not falsy