var google = google || {};
google.Test = google.Test || {};
google.Test.Render = google.Test.Render || {};
What is the difference between the above, and the following.
var MyCompany = MyCompany || {
MyApplication: {
Model: {}
} };
And what is the purpose of the || ?
The first snippet tests whether each level of the namespace exists and if not, it creates it (though the first line should probably be
var google = google || {};).The second one only tests whether the top level exists. For example:
Since
MyCompanyis already defined, this expression evaluates toMyCompany = MyCompany, i.e.MyCompanystays an empty element, the nested objects are not created. If the following code relies onMyCompany.MyApplication‘s existence, it will fail.How
||works is described here: In Javascript, what does it mean when there is a logical operator in a variable declaration?