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 2

Bei Mi Chen
seal-mask
.a{fill-rule:evenodd;}techdegree
Bei Mi Chen
Full Stack JavaScript Techdegree Student 6,720 Points

I did it this way. How can I improve this?

Here's the code:

var questionAnswer = [
  ['Which planet is the closest to the Sun?', 'mercury'],
  ['What\'s the best coding language?', 'javascript'],
  ['What\'s the name of fourth farthest planet from the Sun', 'mars']  
];
var answerCorrect = 0;
var answerWrong = questionAnswer.length; 
var whichRight = "<p> You answered the following correctly: <p> <ol>";
var whichWrong = "<p> You answered the following incorrectly: <p> <ol>";
var results = "<p> You answered " + answerCorrect + " correctly and " + answerWrong + " incorrectly.</p>"; 

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

for( var i = 0; i < questionAnswer.length; i += 1) {
    userAnswer = prompt(questionAnswer[i][0]); 
    if ( userAnswer.toLowerCase() === questionAnswer[i][1]) {
         answerCorrect += 1;
         answerWrong -= 1; 
         whichRight += "<li>" + questionAnswer[i][0] + "</br></li>";
   }  
    else if ( userAnswer.toLowerCase() !== questionAnswer[i][1]) {
        questionsWrong = questionAnswer.indexOf(userAnswer.toLowerCase());
          if ( questionsWrong < 0 ) {
            whichWrong += "<li>" + questionAnswer[i][0] + "</br>" + " The answer is " + questionAnswer[i][1] + "</li>";
      }
   } 
}

if (answerCorrect === 0) {
  whichRight += "Sorry! You answered all questions incorrectly. Please try again."
} else if (answerCorrect === questionAnswer.length) {
  whichWrong += "Congrats! You answered everything correctly!"
}

whichWrong += "</ol>";
whichRight += "</ol>";

print(whichRight);

print(whichWrong);

print(results);

2 Answers

Steven Parker
Steven Parker
231,275 Points

Looks like you nailed it once again. :+1: Keep up the good work!

Hey, this code looks great. I copied it, put it in my editor and ran this to see how it all works.

I believe there may be something wrong with the "results", "answerWrong" & "answerRight" as the print(result) call is always printed 0 right & 3 wrong - in any case. Can someone recheck this and let me know how this can be fixed?