简体   繁体   中英

JavaScript logical operators internals

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM