A quiz app, step by step
A quiz app is the list-and-function idea of Week 12 inside a page. The questions are stored in an array (a list) of objects. Each object holds a text, a list of choices and the index of the right answer, for example answer: 1 means the second choice. Two variables keep the state: index, the number of the question now shown, and score, the number of right answers so far. When the user chooses an answer, the function check(choice) compares the chosen number with questions[index].answer. If they are equal, score goes up by 1. Then index goes up by 1 so the next question is shown. When index equals questions.length, the questions are finished and the page shows the result, such as Score: 2 / 3. In the trace below the pupil chooses 1, 2 and 1. The first answer is right, the second is wrong, the third is right. The questions here are about safe use of a computer and are invented. Remember Week 2: do not click strange links, and tell a trusted adult.
| Step | Chosen | Right? | index | score |
|---|---|---|---|---|
| start | - | - | 0 | 0 |
| 1 | 1 | yes | 1 | 1 |
| 2 | 2 | no | 2 | 1 |
| 3 | 1 | yes | 3 | 2 |
1const questions = [ 2 { text: "A message asks for your password. What do you do?", choices: ["Send it", "Do not click, tell a trusted adult", "Reply with a joke"], answer: 1 }, 3 { text: "Which password idea is strongest?", choices: ["Your name", "A long mix of words and numbers", "The word pass"], answer: 1 }, 4 { text: "A free game asks you to turn off the security program. What do you do?", choices: ["Turn it off", "Ask a teacher first", "Delete the backups"], answer: 1 } 5]; 6let index = 0; 7let score = 0; 8function check(choice) { 9 if (choice === questions[index].answer) { 10 score = score + 1; 11 } 12 index = index + 1; 13}
1if (index === questions.length) { 2 result.textContent = "Score: " + score + " / " + questions.length; 3}
On paper, add a fourth question to the array (an invented one about safe use of a computer, with three choices and an answer index). Then trace the app for the choices 1, 0, 1, 2 and write index and score after each step.