Slippery Rock University Dr. Deborah Whitfield Go Browns!



More IFs

if else if example

A series of if-else-if statements are often used to test all possible values. For this to work, we must test the values in order.
Note that this is closer to the original English statement and that it does include ranges implicitly.

if (average > 90)
  document.write("You earned an A<br>");
else if (average > 80)
  document.write("You earned a B<br>");
else if (average > 70)
  document.write("You earned a C<br>");
else if (average > 60)
  document.write("You earned a D<br>");
else
  document.write("You earned an F<br>");

Another example using ages.


Nested IFs example¹

 if (rain)
  {
     document.formData.weather.src="rain.gif";
     if (car)
     {
        document.formData.travel.src="car.gif";
     }
     else
     {
        document.formData.travel.src="umbrella.gif";
     }
  }
  else
  {
     document.formData.weather.src="sun.gif";
     if (car)
     {
        document.formData.travel.src="car.gif";
     }
     else
     {
        document.formData.travel.src="blank.gif";
     }
  }

Same code as above, but without un-needed { }   example¹

 if (rain)
  {
     document.formData.weather.src="rain.gif";
     if (car)
        document.formData.travel.src="car.gif";
     else
        document.formData.travel.src="umbrella.gif";
  }
  else
  {
     document.formData.weather.src="sun.gif";
     if (car)
        document.formData.travel.src="car.gif";
     else
        document.formData.travel.src="blank.gif";
  }

 

Multi-way selection: The Switch statement

 switch (toDisplay)
 {
   case 1:
     document.formData.display.src="rain.gif";
     break;
   case 2:
     document.formData.display.src="car.gif";
     break;
   case 3:
     document.formData.display.src="umbrella.gif";
     break;
   default:
     document.formData.display.src="sun.gif";
 }
    
 if (toDisplay == 1)
     document.formData.display.src="rain.gif";
 else if (toDisplay == 2)
     document.formData.display.src="car.gif";
 else if (toDisplay == 3)
     document.formData.display.src="umbrella.gif";
 else
     document.formData.display.src="sun.gif";   
    
example¹example¹


¹ The last four examples use forms, Javascript events, and the Document Object Model.
All work herein is subject to copyright. Original content to Dr. Paul Mullins, modifications by Dr. Deborah Whitfield, text content (Head First HTML with CSS & XHTML) to O'Reilly publishing, other tools ( such as HTML-Kit and FireFox) to their respective owners.