Javascript AND operator within assignment

Alex picture Alex · Jul 2, 2010 · Viewed 19.5k times · Source

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.

Answer

Christian C. Salvadó picture Christian C. Salvadó · Jul 2, 2010

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.