Home>Article>Web Front-end> How to use boolean operators in js
There are four types of Boolean operators:
Inversion operator (!)
And operator (&& )
or operator (||)
ternary operator ( ? expression 1 : expression 2 )
negation operator (!)
is used to convert any value into a Boolean value and then into the opposite value, that is, true becomes false, false becomes true
Inversion The operator returns false for the following six values, and returns true for the rest:
undefined
null
''
false
0
NaN
If a value is inverted twice, it is equivalent to converting it into a Boolean value, which has the same effect as the Boolean() function.
!!1 is equivalent to Boolean('1')
and operator(&&)
and operator Used for multiple expressions: Expression 1 && Expression 2
Operation rules: If the first operator returns true, the value of the second operator is returned (not a Boolean value); If the first operator returns false, the first operator is returned and the second operator is no longer evaluated (short circuit)
// 'a'转换为boolean为true,所以直接返回第二个运算子'' 'a' && '' // ''转换为boolean为false,所以直接返回第一个运算子 '' '' && 'a'
or operator (||)
The OR operator is also used for the value of multiple expressions
Operation rules: If the Boolean value of the first operator is true, the first operator is returned directly. The value of an operator; if the Boolean value of the first operator is false, the value of the second operator is returned
// ''的布尔值为false,所以这里返回'b' '' || 'b' // 'b'的布尔值为true,所以这里返回'b' 'b' || ''
or the operator common language sets the default value for a variable
Ternary operator
Expression 1 ? Expression 2 : Expression 3;
If the Boolean value of expression 1 is true, then Returns expression2; if expression1 evaluates to false, returns expression3.
Recommended tutorial:js introductory tutorial
The above is the detailed content of How to use boolean operators in js. For more information, please follow other related articles on the PHP Chinese website!