1

Possible Duplicate:
what’s the javascript “var _gaq = _gaq || []; ” for ?

In the asynchronous example of Google Analytic's Ecommerce tracking code, the declaration of the array is:

var _gaq = _gaq || [];

I'm trying to understand what they are doing here. Is this a true OR statement? Is this because of the async treatment of the script tag?

Thanks!

http://code.google.com/apis/analytics/docs/tracking/gaTrackingEcommerce.html#Example

Community
  • 1
  • 1
Lynn
  • 160
  • 1
  • 8
  • 2
    Same as [what's the javascript "var _gaq = _gaq || \[\]; " for ?](http://stackoverflow.com/questions/2538252/whats-the-javascript-var-gaq-gaq-for) – Matthew Flaschen Jul 15 '10 at 17:08
  • Thanks. I searched before posting and didn't find that answer. Sorry about the repeat. – Lynn Jul 15 '10 at 17:11

2 Answers2

2

If _gaq is false/null, it initializes a new array

It's similar to c#'s null coalesce operator ??

It's a great way to setup defaults on a function

function somefunc (a, b, c) {
   a = a || 1;
   b = b || 2;
   c = c || 3;

   return a + b + c;
}

var result = somefunc();
//result = 6;

var result = somefunc(2,4);
//result = 9;
CaffGeek
  • 21,856
  • 17
  • 100
  • 184
0

|| is called the default operator in javascript. By:

var _gaq = _gaq || [];

They meant: if _gaq is not defined let it be an empty array.

But what it really means is: if _gaq is falsey let it be an empty array.

So beware as the operator is not strictly compares to undefined, rather if the value is falsey. So if you got false, null, NaN or "" (empty string) you may want to avoid this shortcut.

gblazex
  • 49,155
  • 12
  • 98
  • 91