0

what does this means?

var q = [];
var q2 = ["canada","usa","mexico"];
var w = q||q2;
document.writeln(w);

the value of the variable w is : [] the empty list.

can someone explain to me why it is displaying this [] instead of ["canada","usa","mexico"].

DRW02
  • 87
  • 2
  • 9

1 Answers1

1

You should read Logical Operators from MDN. According to the documentation

The logical operator OR (||) expr1 || expr2

Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

In a nutshell, logical operators evaluate from left to right. In your situation, since you have declare q as an empty array ([]), it evaluates to true and immediately goes and assigns w to that.

If you want q2 to take precedence, you can simply do

var w = q2 || q;

so that way only if q2 evaluates to falsey will it assign w to be q instead. The other option is to not declare q at all or declare it as something falsey. You can find out what evaluates to false here.

aug
  • 11,138
  • 9
  • 72
  • 93