Headache Boolean Operators

logic and

1 Grammar specification

&&

2 usage

  1. When there are expressions on both ends of the symbol, the entire expression is true only if the results of both sides are true. As long as one side is flase, the result of the whole expression is flase. That is to say, one false is false

  1. The logical AND operator is a short-circuit operator whose first operand determines the result and the second operand is never evaluated

3 Points to note

The logical AND operator works with operands of any type, not limited to Boolean values. It does not necessarily return a boolean if any operand is not a boolean:

  • If the first operand is an object, returns the second operand

  • If the second operand is an object, the object is returned only if the value of the first operand is true

  • If both operands are objects, returns the second operand

  • Returns null if the first operand is null

  • Returns NaN if the first operand is NaN

  • If the first operand is undefined, returns undefined

4 instances

<script>
        1>2&&console.log(1);
        因为左边表达式为假,所以在控制台不会出输出1
</script>
<script>
        1<2&&console.log(1);、
        左边表达式为真,所以运行右边表达式
</script>

logical or

1 Grammar specification

||

2 usage

  1. When there are expressions at both ends of the symbol, the result of the entire expression is false only if the result of the operation at both ends of the symbol is false. When the result of the operation on the right side is true, the result of the operation of the entire expression is true. That is to say, what is true is true

  1. The logical or operator also has short-circuit characteristics. For logical or, if the first operand is true, the second operand will not be evaluated again

3 Points to note

  • Returns the first operand if the first operand is an object

  • If the first operand is false, return the second operand

  • If both operands are objects, returns the first operand

  • Returns null if both operands are null

  • Returns NaN if both operands are NaN

  • If both operands are undefined, returns undefined

4 instances

<script>
        1<2||console.log(1);
        由于左边表达式为真,所以不运行右边表达式
</script>
<script>
        1>2||console.log(1);
        由于左边表达式为假,所以运行右边表达式
</script>

logical NOT

1 Grammar specification

! (exclamation mark)

2 Rules of use

  1. This operator always returns a Boolean value, no matter what data type it is applied to. The logical NOT operator first converts the operand to a Boolean value and then negates it

  1. Using two exclamation marks (!!) at the same time for a number is equivalent to calling the transformation function Boolean()

console.log(!!"blue")//ture
console.log(!!NAN)//false
console.log(!!12345)//ture

Guess you like

Origin blog.csdn.net/qq_67896626/article/details/129169556