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

Asks questions twice (6 total dialog boxes), but only reports 3 answers. Why is is prompting a second time?

I'm not certain what is happening here. Everything seems to be working except that it repeats the 3 questions via dialog box.

//variable to collect users correct and wrong answers
var correctAnswers = 0 
var wrongAnswers = 0

//array of questions and answers
var questions = [
 [ 'What color is the sky?', 'blue' ],
 [ 'What color is the grass?', 'green' ],
 [ 'What color is the dirt?', 'brown' ]
]

//to ask user each question and store the answer
var questionOne = prompt( questions[0][0] );
var questionTwo = prompt( questions[1][0] );
var questionThree = prompt( questions[2][0] );

//to determine if the answer is correct
var question
var answer
var response
var HTML

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

//display score
HTML = "You got " + correctAnswers + " correct and " + wrongAnswers + " incorrect."
print(HTML);

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

1 Answer

Steven Parker
Steven Parker
231,269 Points

Before the loop begins, this section of the program asks all the questions without checking any of the answers:

//to ask user each question and store the answer
var questionOne = prompt( questions[0][0] );
var questionTwo = prompt( questions[1][0] );
var questionThree = prompt( questions[2][0] );

You can just remove that code, since the questions are asked inside the loop later.