General && and | | Simpler, no discussion here.
Prepare two objects for the discussion below.
Copy Code code as follows:
var Alice = {
Name: "Alice",
Tostring:function () {
return this.name;
}
}
var Smith = {
Name: "Smith",
Tostring:function () {
return this.name;
}
}
in JavaScript, for && not only can be used for Boolean types, it does not just return boolean results.
L returns false directly if the first operand is a Boolean type and the value is false.
L If the first operand is a Boolean and the value is true and the other operand is of type object, then the object is returned.
L If two operands are of type object, then the second object is returned.
L If any one operand is null, then return NULL.
L If any operand is Nan, then return nan.
L If any one operand is undefinded, then return undefined.
Alert (false && Alice); False
Alert (True && Alice); Alice
Alert (Alice && Smith); Smith
Alert (Smith && Alice); Alice
Alert (null && Alice); Null
Alert (NaN && Alice); NaN
Alert (undefined && Alice); Undefined
Alert (Alice && undefined); Undefined
for | | , the same is true not only for Boolean types, but also for boolean-type results.
In fact, null, undefined, and NaN will all be treated as false. And the object is treated as true.
L Returns true directly if the first operand is a Boolean and the value is true.
L If the first operand is a Boolean and the value is false, and the second operand is object, the object is returned.
L If two operands are of type object, then the first object is returned.
L If all two operands are NULL, then NULL is returned.
L Returns nan if all two operands are Nan.
L If all two operands are undefined, then return undefined.
AlertFalse|| Alice); Alice
Alert (true | | | alice); True
Alert (Alice | | smith); Alice
Alert (Smith | | alice); Smith
Alert (null | | | alice); Alice
Alert (Alice | | null); Alice
Alert (null | | null); Null
Alert (NaN | | alice); Alice
Alert (Alice | | NaN); Alice
Alert (NaN | | NaN); NaN
Alert (undefined | | alice); Alice
Alert (Alice | | undefined); Alice
Alert (undefined | | undefined); Undefined
You don't have to be so complicated. Recommend this part of the note
A && B: Converts a, B to a Boolean type, and then performs logic and, True returns B, False returns a
A | | B: Convert a, B to Boolean, and then logic or, True returns a, FALSE returns B
Conversion rules:
Object is True
Non 0 number is true
Non-empty string is true
Other is False
Related articles can refer to the following several, integrated
JS and OR operator | | && Magical
The use of JS and OR operator precedence to implement if else condition to judge an expression
JavaScript && and | | The alternative use technique of operation method