JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

AJ Zhang
AJ Zhang
8,945 Points

the "correctAnswers" only stores the last correct answer

Here is my code for this quiz. I can't get correctAnswers to store the number of correct responses. It only changes to 1 when the 3rd question is answered correctly. I hope I'm making sense... Please help.

function print(message) {
  document.write(message);
}

var questions = [
  ["In which sport would you perform the Fosbury Flop?","the high jump"],
  ["Spinach is high in which mineral?","iron"],
  ["Which type of dog has breeds called Scottish, Welsh and Irish?","terrier"]
];
var question;
var answer;
var response;
var correctAnswers = 0;
var html;

for (var i=0; i<questions.length; i+=1){
  question = questions[i] [0];
  answer = questions[i] [1];
  response = prompt(question);
} if (response.toLowerCase() === answer) {
  correctAnswers +=1;
} 

html="You got " + correctAnswers + " question(s) correct!";
print(html);

2 Answers

I believe it is because your if statement to increment correctAnswers is outside the for loop. Since it is an if statement, it would not increment for every iteration of the loop, only if the answer is correct.

for (var i=0; i<questions.length; i+=1){
  question = questions[i] [0];
  answer = questions[i] [1];
  response = prompt(question);
     if (response.toLowerCase() === answer) {
        correctAnswers +=1;
     } 
} 

This should make your correctAnswers increase by 1 every time a question is correctly answered.

Hope this helps, Dylan

AJ Zhang
AJ Zhang
8,945 Points

Of course! Thank you!