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

Daniel Lee
PLUS
Daniel Lee
Courses Plus Student 566 Points

Counter not working

Everything works except the count doesn't go up. It seems like my code should work but I may be missing something. Please help.

https://w.trhou.se/1zvnnweuz0

2 Answers

andren
andren
28,558 Points

There are two issues:

The first is with this line:

response = parseInt(prompt(question));

You parse the response as an int, but the answers to the questions are not numbers but words. Words can't be converted to numbers so this code will just convert all responses into NaN (Not a Number).

The second issue is in your if statement:

if (response === answer) {
    var correctAnswers = 0;
    correctAnswers += 1;
}

You redeclare the correctAnswer variable and set it equal to 0. Since you do this every time a question is answered correctly correctAnswer will be reset to 0 every time. That first line is not needed at all since the correctAnswer variable already exists outside the if statement.

Here is the fixed code:

var questions = [
  ['What technique is used to remove weight?', 'layers'],
  ['What techique is used to build weight?', 'graduation'],
  ['What technique is used to create weight?', 'one length']
];
var question;
var answer;
var response;
var html;
var correctAnswers = 0;



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

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

function print(message) {
  document.write(message);
}
print(html);
clemhlrdt
clemhlrdt
20,534 Points

In your code, your if statement is always false. Plus, you reset the counter to 0 each time you loop.

response = parseInt(prompt(question)); //parseInt ? You should compare a string to another string ;)
  if (response === answer) {
    correctAnswers += 1;
  }