Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript creates an object that does not exist literally


May 09, 2021 CoffeeScript


Table of contents


Create a literal value of an object that does not exist

Problem

You want to initialize an object literally, but if the object already exists, you don't want to rewrite it.

Solution

Use the existing judgment operator.

window.MY_NAMESPACE ?= {} 

Discuss

This line of code is equivalent to the JavaScript code below:

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

This is a common trick in JavaScript to define namespaces using object literal values. This avoids overrideing a namespace that already exists by determining whether a namespace with the same name exists before it is created.