LEARNING JAVASCRIPT - Trang 116

Table 5-5. Truth table for AND (

&&

) with nonboolean operands

x

y

x && y

falsy

falsy

x

(falsy)

falsy

truthy

x

(falsy)

truthy falsy

y

(falsy)

truthy truthy

y

(truthy)

Table 5-6. Truth table for OR (

||

) with nonboolean operands

x

y

x || y

falsy

falsy

y

(falsy)

falsy

truthy

y

(truthy)

truthy falsy

x

(truthy)

truthy truthy

x

(truthy)

Note that if you convert the result to a boolean, it will be correct according to the

boolean definitions of AND and OR. This behavior of the logical operators allows

you to take certain convenient shortcuts. Here’s one that you will see a lot:

const

options

=

suppliedOptions

||

{

name

:

"Default"

}

Remember that objects (even if they are empty) always evaluate to truthy. So if

suppliedOptions

is an object,

options

will refer to

suppliedOptions

. If no options

were supplied—in which case,

suppliedOptions

will be

null

or

undefined

options

will get some default values.
In the case of NOT, there’s no reasonable way to return anything other than a

boolean, so the NOT operator (

!

) always returns a boolean for an operand of any

type. If the operand is truthy, it returns

false

, and if the operand is falsy, it returns

true

.

Conditional Operator

The conditional operator is JavaScript’s sole ternary operator, meaning it takes three

operands (all other operands take one or two). The conditional operator is the

expression equivalent of an

if...else

statement. Here’s an example of the condi‐

tional operator:

92 | Chapter 5: Expressions and Operators

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.