Skip to content

Commit 2464b33

Browse files
author
Jesse House
committed
new recipe: create object literal if it does not exist
1 parent aa81c4c commit 2464b33

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
layout: recipe
3+
title: Create an object literal if it does not already exist
4+
chapter: Objects
5+
---
6+
7+
h2. Problem
8+
9+
You want to initialize an object literal, but you do not want to overwrite the object if it already exists.
10+
11+
12+
h2. Solution
13+
14+
Use the Existential operator
15+
16+
{% highlight coffeescript %}
17+
window.MY_NAMESPACE ?= {}
18+
{% endhighlight %}
19+
20+
21+
h2. Discussion
22+
23+
This is equivalent to the following JavaScript:
24+
25+
{% highlight javascript %}
26+
window.MY_NAMESPACE = window.MY_NAMESPACE || {};
27+
{% endhighlight %}
28+
29+
Common JavaScript technique, using object literal to define a namespace. This saves us from clobbering the namespace if it already exists.

0 commit comments

Comments
 (0)