ó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:

window.MY_NAMESPACE = window.MY_NAMESPACE || {};

Common JavaScript technique, using object literal to define a namespace. This saves us from clobbering the namespace if it already exists.