Home > Web Front-end > JS Tutorial > body text

How to use boolean operators in js

王林
Release: 2020-05-20 09:27:01
forward
3005 people have browsed it

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'
Copy after login

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' || ''
Copy after login

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!

Related labels:
js
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!