Boolean operators && and | | The return result is not necessarily a Boolean value! Therefore, some research and understanding will be carried out.
1. First introduce the following common data types converted to bool value.
(Common place) in an if expression, JavaScript first converts the conditional expression to a bool value before judging
2. Below to introduce logic and && Logic non | | The returned result after the operation
Logic and &&
It can be seen from the above results. In logic and &&, when the left expression is true, the result returns to the right expression, and the left expression is the result of a false value;
That is
var i= "Truth" && "arbitrary value";=> I result is any value var i= "False value" && "any value"; and the result is left false value
// False value includes null false 0 undefined empty string
Logical OR | |
It can be seen from the above results. Logical OR | | , when the left expression is true, the result returns the left expression, and when the left expression is a false value, the result returns the right-hand expression;
var // The truth value includes a numeric string other than the object function 0 var i= "false values" | | " Any value "; = = I result is ' any value '
3. Logic with && and logic or | | are short-circuit operated.
What is a short-circuit operation, that is, if the first operand can determine the result, then the second operand is no longer evaluated.
var true ; var // An error will occur here // There's no execution .
In the above code, an error occurs when executing the logic and operation, because the variable someundefinevariable is not declared and because found is true, the logical participant evaluates the variable someundefinevariable, Because someundefinevariable is not defined, so will error, if the found is false, then the someundefinevariable will not be evaluated, there will be output results. (PS can no longer be used in logic with undefined values). Logical Non | | Similarly to logic and &&, the right-hand expression is not evaluated when the left-hand expression is true.
Boolean operators in JavaScript && and | |