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.
Although ||
was originally intended to work with booleans, it is implemented in a very handy way that allows it to work to set default values:
function or(a, b) {
if (a) return a
else return b
}
You can test this in your head and see that it works with booleans: if a
is true
, the result is true
so the result is the same as a
. If a
is false
then the result depends on b
.
Variable declarations with var
in JavaScript work a bit strangely. You are allowed to redeclare a variable with the same identifier in the same scope. So the way the code works is:
myNamespace
is already declared, you redeclare the variable without assigning to it yet. You get the value from the old declaration of myNamespace
. This value is assumed to be truthy, so the ||
will return it.myNamespace
is not yet declared, you declare it and then myNamespace
will be undefined
, a falsy value. So the ||
will return the second value, the {}
, and that is the value that will get assigned to myNamespace
.It may make sense to read it in two separate steps:
//Declare the variable if it doesn't exist,
//without overwriting an existing value
var myNamespace
//Take the value of myNamespace (undefined if it didn't exist yet)
//and replace it with {} if it is falsy
myNamespace = myNamespace || {}