Computing the score
Check the answer with if and increment the score counter.
The score accumulator
To keep the count of correct answers we use the accumulator pattern: we start at zero with let score = 0; before the loop, and on each correct answer we add one with score++.
score++ means the same as score = score + 1; it bumps the variable by one. When the loop ends, score holds the total number of correct answers.
Checking with strict equality
To check whether an answer is correct we use the strict equality operator ===. === compares both value and type; == does type conversion and can give surprising results.
The answer field on our question object is a number (for example 1). The value we got from parseInt is also a number. We compare them with ===: userAnswer === q.answer. If they're equal we bump score by one.
Exercise Compute the score
Add a score accumulator to the previous lesson's code. Start it with let score = 0; before the loop. Inside the loop body, compare the userAnswer you got from parseInt with q.answer using ===; if they're equal, bump with score++. After the loop, print the result with console.log("Score:", score).
Show example solution
// Define the quiz questions
const questions = [
{ question: "Capital of Turkey?", options: ["İzmir", "Ankara", "Bursa"], answer: 1 },
{ question: "Wettest city?", options: ["Rize", "Konya", "Ankara"], answer: 0 }
];
// User answers (option indexes as strings)
const userAnswers = ["1", "0"];
let score = 0;
let answerIndex = 0;
for (const q of questions) {
const userAnswer = parseInt(userAnswers[answerIndex]);
if (userAnswer === q.answer) {
score++;
}
answerIndex++;
}
console.log("Score:", score);
Test yourself
-
What does the expression score++ do?
- It resets the score variable
- It doubles the score variable
- It returns the value of score without changing it
- It increases the value of score by one
Show answer
It increases the value of score by one — Correct! score++ is the same as score = score + 1; it adds one.
-
Complete the if condition
if (userAnswer ____ q.answer) { score++; }Show answer
if (userAnswer === q.answer) { score++; } -
Match the expression to its meaning
- let score = 0
- Starts the counter at zero
- userAnswer === q.answer
- Checks correctness with strict equality
- score++
- Increases the score by one
- console.log(score)
- Prints the score to the screen