This article mainly introduces the logical operators & amp;, | and! In JavaScript! Introduction: This article describes the processing rules of logic and & amp;, logic, or | ,! Operators. If you need them, you can refer to them in the same language as C and Java. You can use them in JavaScript ,! Three logical operators are used to perform logical judgment on the boolean value. Unlike C and Java, the logic and (&) and logic operators or (|) Operators in JavaScript can be applied to any value, the return value after the operation is complete is not necessarily a boolean value.
Logic and & processing rules
The processing rules of & in JavaScript are as follows:
1. Determine whether the first value is Falsy. If it is Falsy, the first value (not necessarily boolean) is returned directly ).
2. If the first value is Truthy, the second value is returned directly (not necessarily boolean ).
The Code is as follows:
Var o = {x: 1, y: 2 };
Console. log (o & o. y); // 2
Console. log (null & x); // null
Processing rules of logic or |
Similar to the & operator, the processing rules of | in JavaScript are as follows:
1. Determine whether the first value is Truthy. If it is Truthy, the first value is returned directly (not necessarily boolean ).
2. If the first value is Falsy, the second value is directly returned (not necessarily boolean ).
| This operator makes some convenient JavaScript writing a reality:
1. Obtain the first Truthy value from a series of values:
The Code is as follows:
Var a = null;
Var B = 42;
Var v = a | B | 100;
Console. log (v); // 42
2. Assign the default value to the parameters in the function:
The Code is as follows:
Function test (p ){
P = p | {}; // if p is not passed, make it an empty object.
}
Different from & | ,! The operator behavior is the same as that in C, Java, and other languages. Only boolean values (true or false) are returned ).