Lesson Seven: Functions

  1. Functions allow you to call and execute an entire block of code with one statement.
  2. Your current if statement should look like this:
    if (eventchoice == 1) { document.write(event1); }
    else if (eventchoice == 2) { document.write(event2); }
    else if (eventchoice == 3) { document.write(event3); }
    else if (eventchoice == 4) { document.write(event4); }
    else { document.write(event5); }


  3. To turn a block of code into a function you enclose the code (as shown below) with the function keyword, the name of the function (historyevents in this example), and braces { }. Adjust your code as shown below:
    function historyevents() {
    if (eventchoice == 1) { document.write(event1); }
    else if (eventchoice == 2) { document.write(event2); }
    else if (eventchoice == 3) { document.write(event3); }
    else if (eventchoice == 4) { document.write(event4); }
    else { document.write(event5); }
    }

    Test your program with the new code. Your page should look like this: Sample
  4. No events are written to the page because your code does not currently call the function.
  5. Add this calling code (after the function) to execute the function:
    historyevents();

    Test your program with the new code. Your page should look like this: Sample

Lesson Eight: Parameters