1
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 || ?

epascarello
  • 204,599
  • 20
  • 195
  • 236
kshreve
  • 310
  • 3
  • 14
  • The or basically says, if `google` is null, make the `sample` variable an empty object, rather than setting it to null as well. If `MyCompany` is null, set it to this new object with `MyApplication` in it – Nick Aug 15 '12 at 14:15
  • testing like this `x = x || ...` is dangerous, since `0` and `""` will be overridden too, which sometimes might be a valid value. – Christoph Aug 15 '12 at 14:23
  • 1
    @Christoph: Not in this context though. – Felix Kling Aug 15 '12 at 14:24
  • I changed `var sample = google` to `var google = google` so the example makes sense. – epascarello Aug 15 '12 at 14:34
  • @FelixKling That's why i said sometimes... I think it's important to know, since this method is quite common to set default values for params nowadays. – Christoph Aug 15 '12 at 14:34
  • 1
    doesn't this throw a ReferenceError because google is used before it is defined? – Tom Dec 05 '13 at 14:22

1 Answers1

3

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?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Although if the first test fails, no other levels will exist either so there is no need to test them. F.ex `google = google ? (function() { // test other levels and return google }()) : {};` – David Hellsing Aug 15 '12 at 14:27
  • @David: Ah, you mean if the expression evaluates to `google = {}`? Yes, in that case you would not have to test the existence of the other levels, since they cannot exist, but it's a compact way of creating the namespace. It avoids nasty `if-else` statements and repetition. – Felix Kling Aug 15 '12 at 14:32