Looking at Google’s code for their bookmark bubble library, I came across this:
var google = google || {};
google.bookmarkbubble = google.bookmarkbubble || {};
Could someone explain what it is they’re doing here and why they are doing it? Since JS is an interpreted language why would you ever need to assign the same google object into the google variable? Wouldn’t the script this is contained in only get executed once each time a page is loaded?
They are setting up a namespace-like object. In case there is already a
googleobject orgoogle.bookmarkbubbleobject, they are making sure they don’t replace it. For example, if you had another Google library added, it may have already set up agoogleobject that looks like this:So if they just had:
That would break any code that referenced
google.somelibrary. Likewise, if they didn’t havevar google = google || {};and you didn’t havegooglealready defined, thengoogle.bookmarkbubblewould throw an error.In short, this code ensures that a
google.bookmarkbubbleobject exists without overwriting any previously-definedgoogleorgoogle.bookmarkbubbleobjects.