Like languages such as C and Java, three logical judgements in JavaScript can be used to logically judge the boolean value. Unlike C and Java, the logic and (&&) and logical or (||) operators in JavaScript can be applied to any value, and the returned boolean value may not be necessary after the operation is finished.
Logic and && processing rules
The processing rules of && in JavaScript are as follows:
1. Determine whether the first value is Falsy. If Falsy, the first value is returned directly (not necessarily boolean type).
2. If the first value is Truthy, the second value is directly returned (not necessarily boolean type).
The code copy is as follows:
var o = {x:1, y:2};
console.log(o && oy);//2
console.log(null && x);//null
Logical or ||
Similar to the && operator, the processing rules of || in JavaScript are as follows:
1. Determine whether the first value is Truthy. If Truthy, the first value is returned directly (not necessarily boolean type).
2. If the first value is Falsy, the second value is directly returned (not necessarily boolean type).
This behavior of the || operator makes some shortcut writing methods in JavaScript a reality:
1. Get the first Truthy value from a series of values:
The code copy is as follows:
var a = null;
var b = 42;
var v = a || b || 100;
console.log(v);//42
2. Assign default values to parameters in the function:
The code copy is as follows:
function test(p){
p = p || {};//if p is not passed, make it an empty object.
}
Unlike && and ||, the behavior of the ! operator is consistent with languages such as C, Java, etc., and only returns the boolean value (true or false).