Home  >  Article  >  Web Front-end  >  Introduction to the use of boolean operators in js_javascript skills

Introduction to the use of boolean operators in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:13:501144browse

When we discussed the Boolean operators && and || earlier, I said that their results are Boolean values. This is an oversimplification. If you use them to calculate Boolean data types, they do return Boolean values. But they can also be used to calculate other types of data. In this case, one of the parameters will be returned. What

or operator "||" really does is this: it first checks the parameter on the left. If it is converted into a Boolean value and is true, then the parameter on the left is returned, otherwise Returns the parameter on the right. Think carefully about whether this is the case when both sides of the operator are boolean values. Why does it behave like this? The results of this operation are actually very practical. Let's look at this example:

Copy code The code is as follows:

var input = prompt(" What is your name?", "Kilgore Trout");
alert("Well hello " (input || "dear"));

If the user presses "Cancel" or directly close When the prompt dialog box is closed, the input value will be null or "". In both cases, the value converted to boolean type is false. Then at this time, the expression input || "dear" means that when input has a value, the value of input is obtained, otherwise, "dear" is obtained. This is a very simple way to provide a default value.

works similarly to the "&&" operator, but is the opposite of "||". When the parameter on its left is converted to a Boolean value of "false", it returns that value, otherwise it returns the value on the right. Another feature of these two operators is that the expression on the right side of them will be evaluated only when necessary. In the expression "true || The same goes for "false && X".
Copy code The code is as follows:

false || alert("I'm happening!" );
true || alert("Not me.");
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn