0
votes

While reading the JavaScript documentation I came across a section that confused me:

"Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

&& Operator: expr1 && expr2

(Logical AND) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

|| Operator: expr1 || expr2

(Logical OR) 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."

Let's say you have:

var a3 = false && true; 

so taking into the consideration the rule for the "and" operator, the variable a3 should contain the value true since "false" cannot be converted to false.

1
False can be converted to false trivially, since it is already false. - Patashu
Why can't false be converted to false? false is false. - Blender
True can be converted to false also. Therefore anything can be converted to false? - Robert Rocha
True can't be converted to false. - Patashu

1 Answers

5
votes

The choice of words "can be converted to false" stems from JavaScript having truthy and falsey values.

All values can be converted to a truthy or falsey value.

false is falsey, so no type conversion as such would take place, but other values would convert to false, such as:

undefined, null, NaN, 0, ""

So the and statement would return false and not true, because false is already false and no conversion would be necessary.