Case Statement (Character)

Example of a Case Statement using a Character

<html>
<head>
<script type='text/javascript'>

var Grade = "X" ;

Grade = prompt ('What grade did the student get?') ;

switch (Grade)
{ // begin switch
case 'A':
{ // begin case 1
alert ('Pass of 70 or greater') ;
break ;
} // end case 1

case 'B':
{ // begin case 2
alert ('Pass of 60 to 69') ;
break ;
} // end case 2

case 'C':
{ // begin case 3
alert ('Pass of 50 to 59') ;
break ;
} // end case 3

default :
{ // begin default
alert ('Fail - Score below 50') ;
} // end default

} // end switch

</script>
</head>
<body>
</body>
</html>

A case statement can also be used with a string, although the use of a string is quite rare.

The Case statement is best used when the choices are equally likely, at least approximately.  If one choice is far more likely than the others, it is probably more efficient to pick that off as a special case using an if statement first.  The Case statement could then be part of the Else.

Next: Selection Quiz