JavaScript Project: Quiz Scorer
This project builds a quiz scorer from an array of questions and an array of player answers. One function compares the two arrays, counts the matches, and reports the score.
Step 1: the data
The questions and the player answers are two arrays of the same length. Index 0 in one belongs with index 0 in the other.
const questions = [
{ question: "2 + 2?", answer: "4" },
{ question: "Capital of France?", answer: "Paris" },
{ question: "Color of the sky?", answer: "Blue" }
];
const answers = ["4", "London", "Blue"];
console.log(questions.length, answers.length);Step 2: count the matches
The function walks both arrays by index. It adds one to the score each time the two values match.
const questions = [
{ question: "2 + 2?", answer: "4" },
{ question: "Capital of France?", answer: "Paris" },
{ question: "Color of the sky?", answer: "Blue" }
];
const answers = ["4", "London", "Blue"];
function countScore(questions, answers) {
let score = 0;
for (let i = 0; i < questions.length; i++) {
if (answers[i] === questions[i].answer) {
score++;
}
}
return score;
}
console.log(countScore(questions, answers));Step 3: name the misses
The check now looks for a mismatch instead of a match. A template literal builds a line that names the missed question.
const questions = [
{ question: "2 + 2?", answer: "4" },
{ question: "Capital of France?", answer: "Paris" },
{ question: "Color of the sky?", answer: "Blue" }
];
const answers = ["4", "London", "Blue"];
for (let i = 0; i < questions.length; i++) {
if (answers[i] !== questions[i].answer) {
console.log(`Missed: ${questions[i].question}`);
}
}Example
const questions = [
{ question: "2 + 2?", answer: "4" },
{ question: "Capital of France?", answer: "Paris" },
{ question: "Color of the sky?", answer: "Blue" }
];
const answers = ["4", "London", "Blue"];
function scoreQuiz(questions, answers) {
let score = 0;
for (let i = 0; i < questions.length; i++) {
if (answers[i] === questions[i].answer) {
score++;
} else {
console.log(`Missed: ${questions[i].question}`);
}
}
console.log(`Score: ${score} of ${questions.length}`);
}
scoreQuiz(questions, answers);Key points
- Each question is an object with a question property and an answer property.
- The player answers sit in a second array, in the same order as the questions.
- The scoring function loops by index, so each answer meets its own question.
- A match adds one to the score, and a miss adds a line naming the question.
In this example, scoreQuiz compares each player answer with the answer stored on its question. Two answers match, so the score reaches 2. The missed France question is named, and the final line reports the score out of 3.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
In scoreQuiz, when does the score go up by one?