I've recently come across JavaScript Namespaces and how you can use them to create namespaces like other popular OOP languages. I have confusion on how they are declared. For example,
var myNamespace = myNamespace || {};
creates a namespace called myNamespace
if it hasn't already been created. If it was created, just pass it into var myNamespace
.
I have trouble understanding what myNamespace || {}
actually does.
Wouldn't myNamespace
be undefined at first? How would you compare that in a Boolean expression.
Also, how does the object literal {}
work? Does it create an empty object and assign that to myNamespace
to work as a namespace?
I've tried looking for the answer on SO, but there's too much saturation about the practices on how to declare different types of namespaces.