LEARNING JAVASCRIPT - Trang 100

const

hand

=

[

randFace

(),

randFace

(),

randFace

()];

for

(

let

i

=

0

;

i

<

hand

.

length

;

i

++

)

console.log(

`Roll

${

i

+

1

}

:

${

hand

[

i

]

}

`

);

Useful Control Flow Patterns

Now that you know the basics of control flow constructs in JavaScript, we turn our

attention to some of the common patterns that you’ll encounter.

Using continue to Reduce Conditional Nesting

Very often, in the body of a loop, you’ll only want to continue to execute the body

under certain circumstances (essentially combining a loop control flow with a condi‐

tional control flow). For example:

while

(

funds

>

1

&&

funds

<

100

) {

let

totalBet

=

rand

(

1

,

funds

);

if

(

totalBet

===

13

) {

console

.

log

(

"Unlucky! Skip this round...."

);

}

else

{

// play...

}
}

This is an example of nested control flow; inside the body of the

while

loop, the bulk

of the action is inside the

else

clause; all we do inside the

if

clause is to call

console.log

. We can use

continue

statements to “flatten” this structure:

while

(

funds

>

1

&&

funds

<

100

) {

let

totalBet

=

rand

(

1

,

funds

);

if

(

totalBet

===

13

) {

console

.

log

(

"Unlucky! Skip this round...."

);

continue

;

}

// play...

}

In this simple example, the benefits aren’t immediately obvious, but imagine that the

loop body consisted of not 1 line, but 20; by removing those lines from the nested

control flow, we’re making the code easier to read and understand.

Using break or return to Avoid Unnecessary Computation

If your loop exists solely to find something and then stop, there’s no point in execut‐

ing every step if you find what you’re looking for early.
For example, determining if a number is prime is relatively expensive, computation‐

ally speaking. If you’re looking for the first prime in a list of thousands of numbers, a

naive approach might be:

76 | Chapter 4: Control Flow

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.