Introduction to the use of Boolean operators in js

  • 2020-03-29 23:54:04
  • OfStack

When we talked earlier about Boolean operators & & and | and |, I said that the result is a Boolean. This is a bit of an oversimplification. If you use them to compute Boolean data types, they do return Boolean values. But they can also be used to calculate other types of data, where one of the parameters is returned.

Or the operator "| |" really does this: it first checks the parameter to its left, and if it is true when converted to a Boolean, it returns the parameter to the left, or the parameter to the right. Think about this when you have Boolean values on both sides of an operator. Why does it work this way? The result is very practical. Here's an example:
var input = prompt("What is your name?", "Kilgore Trout"); 
alert("Well hello " + (input || "dear")); 

If the user presses "cancel" or simply closes the prompt dialog box, the value of the input will be null or "". In both cases, the value converted to a Boolean type is false. In this case, || "dear" means that if the input has a value, it will get the value of the input; otherwise, it will get "dear". This is a simple way to provide a default value.

Similar to the operator "&&", but the opposite of "||". When its left argument is converted to a Boolean value of "false", it returns that value, or the right value. Another feature of both operators is that the expression to its right is evaluated only when necessary. In "true |, | X", whatever X is, it's true, so X won't be evaluated, and if X has some other effect, it won't happen. The same goes for false && X.
false || alert("I'm happening!"); 
true || alert("Not me."); 

Related articles: