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:
var MyCompany = {};
// later in the same scope
var MyCompany = MyCompany || { MyApplication: { Model: {} } };
Since MyCompany
is already defined, this expression evaluates to MyCompany = MyCompany
, i.e. MyCompany
stays an empty element, the nested objects are not created. If the following code relies on MyCompany.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?