Home >Web Front-end >JS Tutorial >How Does JavaScript's Logical AND Operator Affect Variable Assignment?
Logical AND Operator in JavaScript Assignment
The assignment of values using the logical AND operator (&&) differs from that of the logical OR operator discussed in the introductory example. While the OR operator assigns the value of the second expression only if the first expression is false, the AND operator behaves differently:
Non-Falsy someOtherVar:
If someOtherVar is not null, undefined, 0, NaN, false, or an empty string (i.e., it is truthy), the AND expression evaluates as true and assigns the value of the second expression to oneOrTheOther. For example:
var someOtherVar = 7; var oneOrTheOther = someOtherVar && "some string"; // oneOrTheOther will be assigned "some string"
Falsy someOtherVar:
However, when someOtherVar is false, the AND expression evaluates as false and assigns the value of the first expression (someOtherVar) to oneOrTheOther. In this case, oneOrTheOther will receive the falsy value of someOtherVar:
var someOtherVar = null; var oneOrTheOther = someOtherVar && "some string"; // oneOrTheOther will be assigned null
This behavior arises from the fact that the AND operator returns the first operand (someOtherVar) when it is falsy to maintain its value (in contrast to the OR operator, which returns the second operand).
The above is the detailed content of How Does JavaScript's Logical AND Operator Affect Variable Assignment?. For more information, please follow other related articles on the PHP Chinese website!