-1

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

doglin
  • 1,651
  • 4
  • 28
  • 38
  • possible duplicate of [What does "var FOO = FOO || {}" mean in Javascript?](http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript) – deceze Jan 09 '14 at 16:31

4 Answers4

1

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.)

cHao
  • 84,970
  • 20
  • 145
  • 172
1

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/

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0

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

Community
  • 1
  • 1
Dan
  • 1,763
  • 4
  • 26
  • 40
0

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();

n1kkou
  • 3,096
  • 2
  • 21
  • 32