Lesson Five: The if else Conditional Statement

  1. JavaScript, like other computer languages, allows you to make decisions in your code based upon a condition.
  2. You can tell the browser that if this is the case then do something, or else do something different.
  3. Replace your document.write() code with this code:
    var eventchoice = 1;
    if (eventchoice == 1) { document.write(event1); }
    else { document.write(event2); }
  4. The above block of code works like this:

    Line one initializes the variable eventchoice and gives eventchoice the value of 1.

    Lines two and three make the conditional statement that if the variable eventchoice is equal to 1 (Note: you are required to use two == equal signs within the conditional statement) then execute the function document.write(event1)
    Lines three and four finish the conditional statement by stating that else (if eventchoice is not equal to 1) then execute the function document.write(event2)

  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.
  6. Your entire second test code should 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 = 2;
    if (eventchoice == 1) { document.write(event1); }
    else { document.write(event2); }

    Sample

Lesson Six: The else if Conditional Statement