Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

AJ Zhang
AJ Zhang
8,946 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,946 Points

Of course! Thank you!