Search code examples
javascriptnamespacesmodule-pattern

Why can't I use var when declaring sub name spaces?


Why does the following work

var NameSpace = NameSpace || {}; 
NameSpace.Foo = 2;

But this does not?

var NameSpace = NameSpace || {}; 
var NameSpace.Foo = 2;

Any insight into the inner workings of the variable deceleration in regards to namespaces would be appreciated.


Solution

  • JavaScript does not have namespaces. Your first line of code is declaring a variable whose name is Namespace, and whose value is an object:

    var NameSpace = NameSpace || {};
    

    Then you create a property Foo on the object, and assign a value to it:

    NameSpace.Foo = 2;
    

    Bottom line: variables and object properties are different things (among other differences, variables have scope, while properties don't). The var statement is only for declaring variables.