I have some questions about javascript namespace

103 views Asked by At

I have run across some Javascript namespace definition. I am a little confused.

Below is a namespace definition correct?

 var googletag = googletag || {};

so when you add a square bracket in the end, what does that mean?

 googletag.cmd = googletag.cmd || [];

when you have a function defined after a namespace what does that mean?

var ctvAdManager = ctvAdManager || {};

(function () {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
        '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
})();

please advise

4

There are 4 answers

0
Sterling Archer On BEST ANSWER

This is shorthand OR notation. In english

var googletag = googletag || {};

Means: "set googletag equal to googletag, but if it is not defined, set googletag to an empty object.

[] is the same, just an empty array instead of an object.

The function notation you used

(function() { ... })(); is called an `Immediately Invoked Function Expression`.

I found this website explains it well. http://benalman.com/news/2010/11/immediately-invoked-function-expression/

0
cHao On

The [] vs {} simply uses an Array vs an Object as the namespace. The former will often work, but is almost always wrong; it pollutes the namespace with the Array prototype properties. ({} does the same with the Object prototype properties, but there are far fewer of those -- and they are less likely to have desirable names.)

0
Dan On

To answer your second question, this function wrapped in parenthesis is a self-executing function. You can read about it here.

0
n1kkou On

var googletag = googletag || {}; will get the value of googletag, or, if googletag is not defined, it will take an empty object.

Same for the second one, but instead of an object, will fallback to an empty array.

For the function:
var foo = 5;
foo == 5 && doSomething(); // is the same thing as if (foo == 5) doSomething(); foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();