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

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

It only asks one question

it only seems to ask the first question and nothing else happens

var questions = [
  ['whats 1+1', 2],
  ['whats 2+2', 4],
  ['whats 1+2', 3]  
];

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

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

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

html = "you got" + correctAnswers + "questions right";
print(html);

2 Answers

malkio kusanagi
malkio kusanagi
12,336 Points

You must separate the looping of user input prompt.

var questions = [
  ['whats 1+1', 2],
  ['whats 2+2', 4],
  ['whats 1+2', 3]  
];

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

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

function ask( response ){
for (var i = 0; i < questions.length; i += 1) {
  questions = questions[i][0];
  answer = questions[i][1];

  if (response === answer) {
    correctAnswers += 1;
return true;
  }
else return false;
}
}



do{
response = parseInt(prompt(questions));
if( ask(response) ){
html = "you got" + correctAnswers + "questions right";
print(html);
}

}while( true != false);

Mod Note - Changed from comment to answer so it may be voted on or marked as best answer.

Hi Sahan Balasuriya, you issue is that instead of using the singular question variable within the loop, you're actually changing the value of the questions (plural) array to equal the first question when you first loop, and then because the length becomes 1, it doesn't loop anymore.

Just change to the following and it should work (note the references to the array still need to be questions):

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