What is “var _gaq = _gaq || []; ” for?

后端 未结 7 1149
梦如初夏
梦如初夏 2020-11-30 02:01

The Async Tracking code in Google Analytics looks like this:

var _gaq = _gaq || []; 
_gaq.push([\'_setAccount\', \'UA-XXXXX-X\']); 
_gaq.push([\'_trackPagev         


        
7条回答
  •  天命终不由人
    2020-11-30 02:47

    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.

提交回复
热议问题