Below javascript statements will cause error, if ga is not declared.
if (ga)
{
alert(ga);
}
The error is:
ga is not defined
It looks undeclared variable cannot be recognized in bool expression. So, why below statement works?
var ga = ga || [];
To me, the ga is treated as bool value before "||". If it is false, expression after "||" is assigned to final ga.
null or defined are falsey values in javascript (implicitly evaluates to false.) the || operator returns the first value that does not evaluate to false.
var x = 0 || "" || null || "hello" || false; // x equals "hello"
On the other hand the && operator will return the first falsey value or the last value.
var y = "a string" && {"attr":"an object"} && false && ["array"];
// y equals false
var z = "a string" && {"attr":"an object"} && ["array"];
// z equals ["array"]
Edit: You need to use var ga;
first or var ga = ga || [];
, because its declare ga first and assign values into it.
You could try this
var x = 1, y = x + 1;
alert([x,y]) // 1,2
You may notice, when y is declare, x is already declared and already assigned 1 to it.
So, in your case, when ga || []
assigns, ga is already declared and its valid variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With