I have two part question about creating namespaces in JavaScript, which one of the following is proper/better way to define a namespace:
// style 1
var company = company || {};
company.models = company.models || {};
company.models.class = {...}
// style 2
company = typeof (company) == 'undefined' ? {} : company;
company.models = company.models || {};
company.models.class = {...}
Please note there are TWO differences in the styles. First is use of typeof and Second is the style 2 does NOT use the var key.
Both these styles seem to work and now here is where it gets really confusing. If I remove the var key from style 1 then namespace does NOT work at all. I get something like company is not defined. I think it has something to do with the var creating a global variable and without var we are creating a global property as explained in here
What is the purpose of the var keyword and when to use it (or omit it)?
Would some please explain to me why the style 1 fails without the var key?
Many thanks in advance.