In js logical operations, 0, "", null, false, undefined, and NaN will all be judged as false, and everything else will be judged as true.
||Calculate the first operand first. If it can be converted to true, return the value of the expression on the left. Otherwise, calculate the second operand. 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.
Take advantage of its feature of returning 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 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 it is not defined, give it an initial value. It is more useful when defining a default value for a function parameter.
&&, it evaluates the first expression first, and if it is false, the second expression will not be processed; otherwise, subsequent expressions 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 && 'sss' The value of the expression is equal to NaN
if(a >=5){
alert("Hello");
}
Can be simplified to:
a >= 5 && alert("Hello");
The difference between typeof 5 and typeof !!5 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 not only help us streamline the code, but also reduce the readability of the code. This requires us to weigh it ourselves.
Clever implementation of startWith function in JS, alert(!'asdf'.indexOf('s')) => !0 = true