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

kevinkrato
kevinkrato
5,452 Points

I'm getting: "you got undefined correct out of 3.you got NaN wrong out of 3." What is wrong with my code??

How can post a photo of my code so its not a giant text blob like below??

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

var questions = [ ['How many states are in the United States?', 50], ['How many legs do insects have?', 6], ['How many continents are there?', 7] ];

var correctAnswers; var wrongAnswers; var answers; var question; var userResponse; var html;

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

html = "you got " + correctAnswers + " correct out of 3."; html += "you got " + wrongAnswers + " wrong out of 3.";

print(html);

2 Answers

Howdy!

There are some issues I found that should fix your issue when corrected.

Firstly, you should check if the answer is correct or wrong after each question, not at the end of the 'for' loop. You have to put that 'if' statement inside the loop. In your code, the 'for' loop ending curly brace is before the 'if' statement.

Secondly, you're incrementing two variables that have no initial value. You should assign 0 to correctAnswers and wrongAnswers when declaring them. The rest is just fine.

Good luck!


This piece of code is working for me:

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

var questions = [ ['How many states are in the United States?', 50], ['How many legs do insects have?', 6], ['How many continents are there?', 7] ];

var correctAnswers=0; var wrongAnswers=0; var answers; var question; var userResponse; var html;

for( var i = 0; i < questions.length; i += 1) { 
    question = questions[i][0]; answer = questions[i][1]; userResponse = parseInt(prompt(question));
    if ( userResponse === answer ) { correctAnswers += 1; } else { wrongAnswers += 1; };
}
html = "you got " + correctAnswers + " correct out of 3."; html += "you got " + wrongAnswers + " wrong out of 3.";

print(html);
Mark Pryce
Mark Pryce
8,804 Points

Take a look at the Markdown Cheatsheet link below the answer box for including code.