What is "var _gaq = _gaq || []; " for? What is "var _gaq = _gaq || []; " for? javascript javascript

What is "var _gaq = _gaq || []; " for?


This line is there to allow multiple GA snippets in the same page. It ensures that the second snippet doesn't overwrite a _gaq defined by the first.

GA asynchronous tracking works by first defining _gaq as an array. This array acts like a queue, which allows you to push (append) configuration and tracking "commands" (like _trackPageview) onto the end of the queue. Your commands are stored in this array until ga.js fully downloads.

When ga.js is ready, it executes all the commands in the _gaq array and replaces _gaq with an object. This object also has a push method, but instead of queueing up commands, it executes them immediately, because ga.js is available to process them.

This mechanism allows you to make configuration and tracking commands without knowing if the browser has finished downloading ga.js. This is needed because the async snippet downloads ga.js without blocking other code on the page from running. Things would get hairy if that other code (your configuration commands) needed to know the state of ga.js being downloaded.

All of this absolutely does depend on the use of the name _gaq. You shouldn't try to name it if you want asynchronous tracking to work.


Yes, it ensures that _gaq is defined, so that _gaq.push() never fails.

I would not mess with the name of the variables in GA's code... do you have any reason to? Does it conflict with any of your variables? (Then I would change mine...)


Using || in assignment is a common programming trick which takes advantage of the evaluation direction of the operator, which is left to right. That means that it evaluates the left side first. Then, and only if that is false (or a false equivalent), does it evaluate the right side.

You can also take advantage of the || or && operators in a simple if statement, so that

if (a > 5) {  do_a();}if (!some_boolean) {  do_b();}

become

a > 5 && do_a();some_boolean || do_b(); // Note that the negation operator `!` is gone!

which are both way nicer to look at.

The reason languages allow this, is because it is a waste of time evaluating the right side if the left side will make the entire line fail anyways. So it just ignores it unless it's needed.