You don't know the && and || (the return value of && and ||)

Today I was bored and wrote the following code on the console.
Insert picture description here
She actually returned.
Insert picture description here
This aroused my great interest, so I found out my rhino collection

Before analyzing this problem, we must first know, in javascript, which represents false

  • Number 0Insert picture description here
  • Empty stringInsert picture description here
  • Boolean falseInsert picture description here
  • nullInsert picture description here
  • undefinedInsert picture description here
  • All except these 6 kinds of NaN Insert picture description here
    ! All! All true

&& operator

  • The result is true when both conditions are true
  • If one is false, the result is false
  • When the first condition is false, the following conditions are no longer judged

See an example

console.log(a && b)

in casea is true, Then it is necessary to judge b, if b is true, then return true, if b is false, then return false, this time b is determined, soReturn b

in casea is false, Then whether b is true or false, it returns false, so there is no need to judge b, this time just judges a, soReturn a

|| Operator

  • As long as one condition is true, the result is true
  • When both conditions are false, the result is false
  • When a condition is true, the following conditions are no longer judged

See an example

console.log(a || b)

in casea is true, Then b returns true regardless of whether it is true or false. So there is no need to judge b, just judge a at this time, soReturn a

in casea is false, Then we have to judge b, if b is true, then return true, if b is false, return false, which is notReturn bYet.

Here is a complicated example

 var a=new Object()
 b=0
 c=Number.NaN
 d=1
 e="Hello";

  alert(a || b && c || d && e);  

The first step The
Insert picture description here
second step is to convert to true or false. The
Insert picture description herethird step is to start the first operation
&& has a higher priority than || oh
Insert picture description here
The fourth step is to start the second calculation. The
Insert picture description here
fifth step is the last calculation.
Insert picture description here
So the final result of this formula is a, which is new Object

Thanks for seeing the end, let’s talk about the principle

Perform Boolean and OR operations. When a certain variable is calculated and the final result is obtained, which variable is returned.

Guess you like

Origin blog.csdn.net/m0_47883103/article/details/108267677