Skip to content

Commit 685b09b

Browse files
kikorbsukima
authored andcommitted
Add more accurate details on CS ?= opperator (coffeescript-cookbook#146)
* Update object-literal.md The example was wrong. It stated that ?= is similar to JS || when the || will affect not only not defined scenario but also any falsy values (values that evaluate as false) There are way to many differences between the 2: 1. window.var = false; 2. window.var = 0; 3. window.var = ''; 4. window.var = []; 5. window.var = null; window.var ?= 'something' console.log(window.var) -> 1. false 2. 0 3. '' 4. [] 5. 'something' window.var ||= 'something' console.log(window.var) -> 1. 'something' 2. 'something' 3. 'something' 4. [] 5. 'something' * Update object-literal.md * Update object-literal.md
1 parent 7ff9e5c commit 685b09b

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

chapters/classes_and_objects/object-literal.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,29 @@ window.MY_NAMESPACE ?= {}
2020
This is equivalent to the following JavaScript:
2121

2222
{% highlight javascript %}
23-
window.MY_NAMESPACE = window.MY_NAMESPACE || {};
23+
if(window.MY_NAMESPACE === null || window.MY_NAMESPACE === undefined) {
24+
window.MY_NAMESPACE = {};
25+
}
2426
{% endhighlight %}
2527

26-
Common JavaScript technique, using object literal to define a namespace. This saves us from clobbering the namespace if it already exists.
28+
## Problem
29+
30+
You want to make a conditonal assignment if it does not exists or if it is falsy (empty, 0, null, false)
31+
32+
## Solution
33+
34+
Use the Conditional assignment operator
35+
36+
{% highlight coffeescript %}
37+
window.my_variable ||= {}
38+
{% endhighlight %}
39+
40+
## Discussion
41+
42+
This is equivalent to the following JavaScript:
43+
44+
{% highlight javascript %}
45+
window.my_variable = window.my_variable || {};
46+
{% endhighlight %}
47+
48+
Common JavaScript technique, using conditional assignment to ensure that we have an object that is not falsy

0 commit comments

Comments
 (0)