javascriptnamespacesjavascript-namespaces

JavaScript namespace object literal


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.


Solution

  • 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:

    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 || {}