Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JavaScript Statement "ga = ga || []" Works?

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.

like image 737
Morgan Cheng Avatar asked Apr 21 '10 03:04

Morgan Cheng


2 Answers

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"] 
like image 114
Kenneth J Avatar answered Oct 05 '22 23:10

Kenneth J


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.

like image 24
YOU Avatar answered Oct 05 '22 22:10

YOU