I know that in JavaScript you can do:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
where the variable oneOrTheOther
will take on the value of the first expression if it is not null
, undefined
, or false
. In which case it gets assigned to the value of the second statement.
However, what does the variable oneOrTheOther
get assigned to when we use the logical AND operator?
var oneOrTheOther = someOtherVar && "some string";
What would happen when someOtherVar
is non-false?
What would happen when someOtherVar
is false?
Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.
Basically, the Logical AND operator (&&
), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:
true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything"; // 0
Note that falsy values are those that coerce to false
when used in boolean context, they are null
, undefined
, 0
, NaN
, an empty string, and of course false
, anything else coerces to true
.