Today I was bored and wrote the following code on the console.
She actually returned.
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 0
- Empty string
- Boolean false
- null
- undefined
- All except these 6 kinds of NaN
! 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
second step is to convert to true or false. The
third step is to start the first operation
&& has a higher priority than || oh
The fourth step is to start the second calculation. The
fifth step is the last calculation.
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.