Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions chapters/classes_and_objects/object-literal.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,29 @@ window.MY_NAMESPACE ?= {}
This is equivalent to the following JavaScript:

{% highlight javascript %}
window.MY_NAMESPACE = window.MY_NAMESPACE || {};
if(window.MY_NAMESPACE == null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since type coercion is the crux of the PR maybe this coerced comparison should also be expanded:

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

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you 👍

window.MY_NAMESPACE = window.MY_NAMESPACE
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean window.MY_NAMESPACE = {};?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, sorry for noticing the typo, I did the changes quickly and that is never a good idea. 👍

}
{% endhighlight %}

Common JavaScript technique, using object literal to define a namespace. This saves us from clobbering the namespace if it already exists.
## 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

{% highlight coffeescript %}
window.my_variable ||= {}
{% endhighlight %}

## Discussion

This is equivalent to the following JavaScript:

{% highlight javascript %}
window.my_variable = window.my_variable || {};
{% endhighlight %}

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