2

Possible Duplicates:
In Javascript, what does it mean when there is a logical operator in a variable declaration?
what’s the javascript “var _gaq = _gaq || []; ” for ?

what does this javascript syntax mean?

var _gaq = _gaq || [];
Community
  • 1
  • 1
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • 1
    duplicate of: [what’s the javascript `var _gaq = _gaq || \[\];` for ?](http://stackoverflow.com/questions/2538252/whats-the-javascript-var-gaq-gaq-for) and see this similar question: http://stackoverflow.com/questions/3088098/in-javascript-what-does-it-mean-when-there-is-a-logical-operator-in-a-variable-declaration – Christian C. Salvadó Jun 23 '10 at 19:11
  • 1
    IMO I think it is just bad code, if you declare `_gaq` with the `var` statement, it will shadow *any* other variable named `_gaq`, higher in the scope chain... – Christian C. Salvadó Jun 23 '10 at 19:18
  • @CMS – Unless you already are in the global scope, which is the case. But even then `var` isn't necessary. – Marcel Korpel Jun 23 '10 at 20:32
  • @Marcel, yeah, the only difference in global code between using `var` or not, is that when you use `var` the identifier is bound to the Variable Object (which is the global object itself for global code) it is marked as non-deleteable. E.g. `var foo = ''; bar = '';` then `delete foo == false;` and `delete bar == true;` – Christian C. Salvadó Jun 23 '10 at 20:46

3 Answers3

10

it means assign _gaq the value of _gaq unless it is undefined, in which case _gaq will be an empty list.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
3

It's a short way to set _gaq to an empty array if _gaq is undefined. It's probably used to provide a default value for an argument to a function.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
2
_gaq || []

Is an expression that will return _gaq if it's a non-false value ( I mean is not 0, nor false, nor '') or an empty array in the other case.

var _gaq = _gaq || [];

Always will set [] to _gaq. I tested it in this way from my firebug console:

_gaq = 'crazy value';
(function(){var _gaq = _gaq || []; 
            console.log(_gaq);
 })();

Having in mind that _gaq could be a variable defined in the global namespace. But is not the case.

mati
  • 5,218
  • 3
  • 32
  • 49
  • I think this is the best answer and deserves it to be marked as such (unless mentioned code *is* run in global scope, and I think it is). It clearly elaborates CMS' comment on the question. +10 if I could. – Marcel Korpel Jun 23 '10 at 20:24