LEARNING JAVASCRIPT - Trang 115

Short-Circuit Evaluation

If you look at the truth table for AND (

Table 5-2

), you’ll notice you can take a short‐

cut: if

x

is falsy, you don’t even need to consider the value of

y

. Similarly, if you’re

evaluating

x || y

, and

x

is truthy, you don’t need to evaluate

y

. JavaScript does

exactly this, and it’s known as short-circuit evaluation.
Why is short-circuit evaluation important? Because if the second operand has side

effects, they will not happen if the evaluation is short-circuited. Very often, the term

“side effect” is taken to be a bad thing in programming, but it isn’t always: if the side

effect is intentional and clear, then it’s not a bad thing.
In an expression, side effects can arise from incrementing, decrementing, assignment,

and function calls. We’ve already covered increment and decrement operators, so let’s

see an example:

const

skipIt

=

true

;

let

x

=

0

;

const

result

=

skipIt

||

x

++

;

The second line in that example has a direct result, stored in the variable

result

. That

value will be

true

because the first operand (

skipIt

) is

true

. What’s interesting,

though, is because of the short-circuit evaluation, the increment expression isn’t eval‐

uated, leaving the value of

x

at

0

. If you change

skipIt

to

false

, then both parts of

the expression have to be evaluated, so the increment will execute: the increment is

the side effect. The same thing happens in reverse with AND:

const

doIt

=

false

;

let

x

=

0

;

const

result

=

doIt

&&

x

++

;

Again, JavaScript will not evaluate the second operand, which contains the increment,

because the first operand to AND is

false

. So

result

will be

false

, and

x

will not be

incremented. What happens if you change

doIt

to

true

? JavaScript has to evaluate

both operands, so the increment will happen, and

result

will be

0

. Wait, what? Why

is

result 0

and not

false

? The answer to that question brings us neatly to our next

subject.

Logical Operators with Nonboolean Operands

If you are using boolean operands, the logical operators always return booleans. If

you’re not, however, the value that determined the outcome gets returned, as Tables

5-5

and

5-6

show.

AND, OR, and NOT | 91

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.