Example 1

The code shown here is a version of the High/Low Card game where a player is shown a playing card and has to decide whether the next card will be higher or lower. Comments have been added to the code.

<html>
 <head>
 <script language='JavaScript'>

// Data
// Declare and initialise both cards to 0
 var FirstCard = 0 ;
 var SecondCard = 0 ;
 // Declare and initialise choice as X
 var Choice = 'X' ;

function DealCards()
 { // begin DealCards
 // Get a random number between 1 and 13 for each card
 // 11 = Jack, 12 = Queen and 13 = King and Ace = 1 only
 FirstCard = Math.floor((Math.random() * 13) + 1) ;
 SecondCard = Math.floor((Math.random() * 13) + 1) ;
 } // end DealCards

function GoHigher()
 { // begin GoHigher
 if (SecondCard > FirstCard)
 { // begin if
 alert ('Second card = ' + SecondCard + ' which is higher than the first card = ' 
       + FirstCard + ' - You win!')
 } // end if
 else
 { // begin else
 alert ('Second card = ' + SecondCard + ' which is lower or equal to the first card = ' 
       + FirstCard + ' - You lose!')
 } // end else
 } // end GoHigher

function GoLower()
 { // begin GoLower

if (SecondCard < FirstCard)
{ // begin if
alert ('Second card = ' + SecondCard + ' which is lower than the first card = ' 
      + FirstCard + ' - You win!')
} // end if
else
{ // begin else
alert ('Second card: ' + SecondCard + ' which is higher or equal to the first card = ' 
      + FirstCard + ' - You lose!')
} // end else

// Main Program
DealCards() ; // Call the DealCards function to get the two cards

// Get the player's choice but only display the FirstCard

Choice = prompt ('First card = ' + FirstCard + ' Type H for Higher or L for Lower: ') ;

// Changes possible lowercase input of Choice to upper case
Choice = Choice.toUpperCase();

if (Choice.toUpperCase() == 'H') // Player chooses Higher
{ // begin if
GoHigher() ;
} // end if
else // Player chooses Lower
{ // begin else
GoLower () ;
} // end else

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

Next: Example 2