LEARNING JAVASCRIPT - Trang 98

You can also specify a special case, called

default

, that will be used if no other case

matches. It is conventional (but not required) to put the default case last:

switch

(

totalBet

) {

case

7

:

totalBet

=

funds

;

break

;

case

13

:

funds

=

funds

-

1

;

// give 1 pence to charity!

case

11

:

totalBet

=

0

;

break

;

case

21

:

totalBet

=

21

;

break

;

default

:

console

.

log

(

"No superstition here!"

);

break

;

}

The

break

is unnecessary because no cases follow

default

, but always providing a

break

statement is a good habit to get into. Even if you’re using fall-through execu‐

tion, you should get into the habit of including

break

statements: you can always

replace a

break

statement with a comment to enable fall-through execution, but

omitting a

break

statement when it is correct can be a very difficult-to-locate defect.

The one exception to this rule of thumb is if you are using a

switch

statement inside

a function (see

Chapter 6

), you can replace

break

statements with

return

statements

(because they immediately exit the function):

function

adjustBet

(

totalBet

,

funds

) {

switch

(

totalBet

) {

case

7

:

return

funds

;

case

13

:

return

0

;

default

:

return

totalBet

;

}
}

As usual, JavaScript doesn’t care how much whitespace you use, so it’s quite common

to put the

break

(or

return

) on the same line to make

switch

statements more

compact:

switch

(

totalBet

) {

case

7

:

totalBet

=

funds

;

break

;

case

11

:

totalBet

=

0

;

break

;

case

13

:

totalBet

=

0

;

break

;

case

21

:

totalBet

=

21

;

break

;

}

74 | Chapter 4: Control Flow