Lesson Six: The else if Conditional Statement

  1. The if else conditional statement only allows for two possible results. However, there will be times when you want to evaluate more than two possibilities.
    For these occasions you can use the else if statement.
  2. Add this else if code to your if else code block:
    else if (eventchoice == 2) { document.write(event2); }
  3. Your entire JavaScript file should now look like this:
    var event1;
    event1 = "488 Million Years Ago the Mollusks Appeared";
    var event2 = "250 Million Years Ago the Dinosaurs Appeared";
    var event3 = "65 Million Years Ago - Age of the Mammals";
    var eventchoice = 3;
    if (eventchoice == 1) { document.write(event1); }
    else if (eventchoice == 2) { document.write(event2); }
    else { document.write(event3); }
  4. The if block of code works like this:

    Line six evaluates the eventchoice variable that is set to 3 and determines that the variable is not 1.
    Therefore, the program proceeds to the
    else if statement on line 7.
    Line 7 evaluates the
    eventchoice variable (set to 3) and determines that the variable is not 2.
    Therefore, the program proceeds to the
    else statement on line 8.
    The
    else statement on line 8 allows for the the execution of the document.write(event3) function.
    The contents of the variable event3 (65 Million Years Ago - Age of the Mammals) is written to the page.

  5. Test the program with the eventchoice variable having the value of 1 and then test the program with the eventchoice variable set to 2.

Lesson Seven: Functions