开发者

What does _gaq || [] accomplish for Google Analytics Ecommerce tracking? [duplicate]

This question already has answers here: Closed 12 years ago.

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 understan开发者_Go百科d 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


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜