Like C, Java and other languages, JavaScript can use &&, | |,! Three logical judges to logically judge a Boolean value. Unlike C and Java, the logic in JavaScript (&&) and logic or (| |) The operator can be applied to any value, and it is not necessarily a Boolean value to return after the operation ends.
Rules for handling logic and &&
The processing rules for && in JavaScript are as follows:
1. Determine whether the first value is Falsy. If Falsy, the first value is returned directly (not necessarily a Boolean type).
2. If the first value is Truthy, the second value is returned directly (not necessarily a Boolean type).
Copy Code code as follows:
var o = {x:1, y:2};
Console.log (o && o.y);//2
Console.log (null && x);//null
Logic or | | The processing rules
Similar to the && operator, JavaScript | | The processing rules are as follows:
1. Determine whether the first value is truthy. If Truthy, the first value is returned directly (not necessarily a Boolean type).
2. If the first value is Falsy, the second value is returned directly (not necessarily a Boolean type).
|| This behavior of the operator makes some shortcuts in JavaScript a reality:
1. Get the first Truthy value from a series of values:
Copy Code code as follows:
var a = null;
var B = 42;
var v = a | | B | | 100;
Console.log (v);//42
2. Assign a default value to a parameter in a function:
Copy Code code as follows:
function Test (p) {
p = P | | {};//if P is isn't passed, make it a empty object.
}
With && and | | Different,! The behavior of the operator is consistent with languages such as C and Java, and only Boolean values (TRUE or FALSE) are returned.