Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Annalee Pawlowski
Annalee Pawlowski
1,144 Points

if statement within the for loop is not incrementing the "correctAnswers" variable - even though syntax looks correct

correctAnswers variable always comes back as 0 even when getting questions right and should be incrementing. The problem appears to be happening in the for loop if statement.

var quizQuestions = [
  [ 'What is the color of the sun?' , 'Yellow' ] ,
  [ 'What is the color of the grass?' , 'Green' ] ,
  [ 'What is the color of the sky?' , 'Blue'] ,
];

  var correctAnswers = 0;
  var question;
  var answer;
  var response;
  var html;

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

// Ask the questions

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

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

}

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

Can you try in for loop for the last statement i++

1 Answer

Since you convert your responses to lowercase and all your answers are in title case they will never be equal. One easy fix is to change your answers to lowercase.

Annalee Pawlowski
Annalee Pawlowski
1,144 Points

Thank you! For some reason I thought the toLowerCase was also converting the question string but now the error seems obvious. Thanks!