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

Can't get correct question counter to go up

I've tried it a million different ways, but my correctGuesses counter just doesn't go up with each iteration of the for loop. The correct questions are added to the list, but the counter stays at 0 for some reason.

Can someone have a look into it?

var quiz = [
    ["What kind of object did Genie from Alladin come from?", "lamp"],
    ["What is Pedro's most played single player game of all time?", "monster hunter"],
    ["What programming language was this quiz written in?", "javascript"]
];

var correctGuesses = 0;

var correctQuestions = "<h1>Grats! You got " + correctGuesses + " questions correct. </h1> <h2> You got these right:</h2><ol>";

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

for (var i = 0; i < quiz.length; i++) {
    var userAnswer = prompt(quiz[i][0]);
    if (userAnswer.toLowerCase() === quiz[i][1]) {
        correctGuesses++;
        correctQuestions += "<li>" + quiz[i][0] + "</li>";
    }
}

correctQuestions += "</ol>";
print(correctQuestions);

1 Answer

Steven Parker
Steven Parker
229,744 Points

:point_right: Your code builds the first line of the result before asking the questions.

In fact, it's the very next line after setting correctGuesses to 0.

If you want to display the final result, you''ll need to build the result string after the score has been accumulated in the loop.

Hehe yeah, I fixed it just before I checked back :)

Realized I was setting the string to have the value of 0, and only after updating the counter to be more than that, which is not retroactive :) Thank you very much for taking the time! I was stumped for over an hour and it feels so silly now!