mikkelbreum
mikkelbreum

Reputation: 3081

javascript: is this a conditional assignment?

From the google analytics tracking code:

var _gaq = _gaq || [];

how does this work?

Is it a conditional variable value assignment? Is it the same as saying:

if( !(_gaq) ) {_gaq = []; }

?

Upvotes: 15

Views: 12500

Answers (4)

Brett Zamir
Brett Zamir

Reputation: 14365

It's the same as saying:

if( !(_gaq) ) {var _gaq = [];}

(This can be done since the var is hoisted above the conditional check, thereby avoiding a 'not defined' error, and it will also cause _gaq to be automatically treated as local in scope.)

Upvotes: 2

Pointy
Pointy

Reputation: 413996

Actually it's not the same as saying:

if (!_gaq) _gaq = [];

at least not necessarily. Consider this:

function outer() {
  var _gaq = null;
  function inner() {
    var _gaq = _gaq || [];
    // ...
  }

  inner();
  _gaq = 1;
  inner();
}

When there's a "_gaq" (I hate typing that, by the way) in an outer lexical scope, what you end up with is a new variable in the inner scope. The "if" statement differs in that very important way — there would only be one "_gaq" in that case.

Upvotes: 1

SLaks
SLaks

Reputation: 888185

Yes, it is.

The || operator evaluates to its leftmost "truthy" operand.
If _gaq is "falsy" (such as null, undefined, or 0), it will evaluate to the right side ([]).

Upvotes: 5

Quentin
Quentin

Reputation: 944441

The or operator (||) will return the left hand side if it is a true value, otherwise it will return the right hand side.

It is very similar to your second example, but since it makes use of the var keyword, it also establishes a local scope for the variable.

Upvotes: 15

Related Questions