In the previous chapter we declared the arrays that hold the questions and answers for our trivia quiz. We also populated these arrays with the first three questions. At that point we didn't have enough knowledge to actually make use of the data, but with what we've learned in this chapter, we can create a function that uses the information in the arrays to check whether an answer is correct.
Load in trivia_quiz.htm and alter it to that shown here:
The only changes here are that we've removed the alert() function, which told the user that the array was initialized, and added a function, answerCorrect(), which checks whether a trivia question has been answered correctly. This function has been added inside the script block in the head of the page. The answerCorrect() function takes two parameters: the question index from the arrays in the parameter questionNumber and the answer the user has given in the parameter answer. It then checks whether the user's answer is in fact correct—if it is, the function returns true, otherwise it returns false.
Currently the code checks the answer given by the user by checking to see whether the element of the answers array with an index of questionNumber is equal to the answer parameter. Given how simple this function is, couldn't we have just included the code wherever it's needed? Why go to the bother of creating a function? The answer to this query is that we have plans for that function. Currently, its role is simply to check whether the multiple-choice response, a single letter given by the user, is the same as the letter stored in the answers array. However, later we'll expand the trivia quiz to handle text-based questions such as, "Which President was involved in the Watergate scandal?" and we want the answer to be considered correct whether the user enters Richard Nixon, Nixon, R Nixon, and so on. This involves more than a simple comparison, so at some point we'll expand the answerCorrect() function to incorporate this extra intelligence. By including it in just one function, we need to change our code in only one place and can do so without breaking other parts of our program. Code using our function expects only a true or false result—how this function comes by this result is irrelevant.
To test our new answerCorrect() function, let's write some code that goes through each of the questions in the questions array and uses the answerCorrect() function to work out which answer is correct. Insert the following lines into the body of the page, inside the script block after the questions and answers array have been defined. Once you've finished testing, you can delete this code because it does not form part of the final trivia quiz.
The code writes all the answers to the page by accessing the answer array and getting the letter in there that corresponds to the correct answer for each question.
If you load trivia_quiz.htm into your browser, you should see what is shown in Figure 3-14.