JS logic or | Summary of logic and & usage, and logic in js
JS logic or | Summary of logic and & Usage
// 1. In the if judgment
// If (1 = 1 | 2 = 3) {}//-> if either of the two conditions is true, the whole is true "or"
// If (1 = 1 & 2 = 3) {}//-> both conditions are true, and the whole condition is true. "and"
// 2. When either of the two values is obtained
// 1 | 2-> 1 "logic or" First, check whether the value on the left is true or false. If it is true, the value on the left is returned, false returns the right value.
// 1 & 2-> 2 "logic and" First, check whether the value on the left is true or false. If it is true, the return value is the value on the right, false returns the value on the left.
// How to check whether it is true or false?
// Only 0, NaN, null, undefined, and null strings are false, and others are true.
// We apply logic or initialize data in real projects
// Requirement: Calculate the sum of two numbers. If the second number is not passed, we add zero by default.
Function sum (num1, num2 ){
// If (typeof num2 = "undefined") {//-> indicates that num2 has not passed the value. The default value is undefined. In this case, the value is changed to 0.
// Num2 = 0;
//}
Num2 = num2 | 0; //-> undefined | 0-> num2 = 0 is equivalent to the above judgment.
Console. log (num1 + num2 );
}
// Sum (100); //-> num1 = 100 num2 = undefined
// 3. When | and & appear at the same time, the priority of & is greater than |
Console. log (0 | 1 & 2 | 3 );
// 1 & 2-> 2
// 0 | 2-> 2
// 2 | 3-> 2