Before we discussed the Boolean operators && and | | , I said that their result is a Boolean value. It's a bit simplistic to say. If you use them to compute Boolean data types, they do return Boolean values. But they can also be used to compute other types of data, at which point the return will be one of the parameters.
Or operator "| |" The real thing to do is this: it first checks its left parameter, and if it converts to a Boolean-type value, returns the argument to the left, or the right argument. Think about this when the operator is both on both sides of a Boolean type value. Why does it run like this? The result of this operation is actually very practical. Let's look at this example:
Copy Code code as follows:
var input = prompt ("What is your name", "Kilgore Trout");
alert ("OK Hello" + (Input | |) Dear "));
If the user presses "Cancel" or simply turns off the prompt dialog box, the input value will be null or "". In either case, the value converted to a Boolean type is false. Then input | | "Dear" This expression means that input has a value when the value of input, or get "dear". This is a very simple way to provide a default value.
The operator "&&" works like this, but it's the opposite of "| |". When its left argument converts a Boolean to a value of "false", it returns that value, otherwise it returns the value on the right. Another feature of the two operators is that the value of the expression on the right is evaluated only when necessary. On the true | | X "In this expression, no matter what x is, the result is true, so X is not computed, and if X has other effects, the effect is not generated." "False && X" is the same reason.
Copy Code code as follows:
False | | Alert ("I ' m happening!");
true | | Alert ("Not me.");