In js logical operations, 0, "", null, false, undefined, and NaN will all be judged as false, and others will be true.
|| Calculate the first operand first, if it can be If converted to true, the value of the expression on the left is returned, otherwise the second operand is calculated. Even if the operand of the || operator is not a Boolean value, it can still be regarded as a Boolean OR operation, because no matter what type the value it returns is, it can be converted to a Boolean value.
Use the feature that it will return non-Boolean values: use || for non-Boolean operands to select the first defined and non-null value in a set of alternative values. (The first one is a non-false value)
Example:
var max = max_width || obj.max_width || 500 ;
var attr = attr || "";This operation is often used To determine whether a variable has been defined, if not defined, give it an initial value, which is more useful when defining a default value for a function parameter.
&&, it evaluates the first expression first. If it is false, the second expression will not be processed; otherwise, the subsequent expression will continue to be processed. Selects the value of the first non-true expression from left to right, and returns the value of the last expression if it is not found.
Example: (the taste needs to be carefully considered)
2 && 's1' && '123' && 'sss' The value of the expression is equal to 'sss'
2 && ' s1' && '' && 'sss' The value of the expression is equal to ''
2 && 's1' && NaN && The value of 'sss' expression is equal to NaN
if(a >=5) {
alert("Hello");
}
can be simplified to:
a >= 5 && alert("Hello");
typeof 5 and typeof The difference between !!5, this is a more rigorous way of writing, the function of !! is to convert a variable of other types into the bool type. For example, if(!!attr) => if(attr)
The features of || and && in js help us streamline the code, but also reduce the readability of the code. This requires us to weigh it ourselves.
Ingenious implementation of startWith function in JS, alert(!'asdf'.indexOf('s')) =》 !0 = true