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

Script breaks... loop dosent work... Why?

==

Why dosent the loop work?

var correctCount = 0; // correct answer count
var wrongCount = 0; // wrong answer count

//save correct and incorect answers 
var correctAnswers = [];
var incorrectAnswers = [];

//question array 
var questions = [
  ["1+1=?", 2],
  ["2+2=?", 4],
  ["3+3=?", 6],
  ["4+4=?", 8]
];

//loop
for (var i=0; i < questions.length; i++) {
  var question = questions[i][0]); //question
  var answer = questions[i][1]); // correct answer
  var response = parseInt(prompt(question)); //user answer

 if (answer == response) {
     correctCount +=1;
     correctAnswers.push(questions[i]);

} else {
      wrongCount +=1;
      incorrectAnswers.push (questions[i]);
}


console.log (correctCount);
console.log (correctAnswers.join(", "));
console.log (wrongCount);
console.log (incorrectAnswers.join(", "));

3 Answers

1- in your ' if ' and ' console log ' you have to use -iNcorectanswers- ( you forgot N )

2- correctanswers and incorrectanswers, you declared them as arrays, you cant assign to thema value like this a += value. you use a the push meethod :)

correctAnswers.push(Questions[i]);

3- you have to parseInt your prompt, cause you ll have a string in return .

Made the chages but the loop doesnt work.....

//question array 
var questions = [
  ["1+1=?", 2],
  ["2+2=?", 4],
  ["3+3=?", 6],
  ["4+4=?", 8]
];

//loop
for (var i=0; i < questions.length; i++) {
  var question = questions[i][0]); //question
  var answer = questions[i][1]); // correct answer
  var response = parseInt(prompt(question)); //user answer
 }

In your for loop, your question and answer variables have a closing parentheses at the end without any corresponding opening parentheses before them. Just remove that on both of those and you should be good.

for (var i=0; i < questions.length; i++) {
  var question = questions[i][0]); 
                             // ^ Remove this
  var answer = questions[i][1]); 
                           // ^ Remove this
  var response = parseInt(prompt(question)); 
 }

Your if-clause needs a double equal sign for the comparison: if (allQuestions[i][1] == prompt(allQuestions[i][0])) = assigns a value, == compares two values.

Still get an error....

remove i++ and replace it with i+= 1. just to make sure !