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
SAMUEL LAWRENCE
Courses Plus Student 8,447 PointsWhy am I getting an `undefined` message in my preview?
Hi guys for the quiz challenge I changed my code a bit so that it would print only correct answers if the player got all the answers correct or only wrong answers if they got all wrong and print both correct and wrong if they only got some correct. However, I'm getting an undefined printed at the top of my page and I can't figure out why. Can you look at my code and tell me what I'm missing? thanks.
questions = [
{
question: 'What is 25 x 2?',
answer: 50
},
{
question: 'How many continents are there?',
answer: 7
},
{
question: 'How many legs does an insect have?',
answer: 6
}
];
function buildList (arr) {
var listHTML = '<ol>';
for (var i = 0; i < arr.length; i += 1) {
listHTML += '<li>' + arr[i] + '</li>';
}
listHTML += '</ol>';
return listHTML;
}
var correctAnswers = 0;
var question;
var answer;
var response;
var html;
var correct = [];
var wrong = [];
function print(message) {
document.write(message);
}
for (var i = 0; i < questions.length; i += 1){
question = questions[i].question;
answer = questions[i].answer;
response = parseInt(prompt(question));
if (response === answer) {
correctAnswers += 1;
correct.push(question);
} else {
wrong.push(question);
}
}
html += '<p>You got ' + correctAnswers + ' questions right.</p>';
if (correctAnswers === 3) {
html += '<h2>You got these questions right</h2>';
html += buildList(correct);
} else if ( correctAnswers === 0){
html += '<h2>You got these questions wrong</h2>';
html += buildList(wrong);
} else {
html += '<h2>You got these questions right</h2>';
html += buildList(correct);
html += '<h2>You got these questions wrong</h2>';
html += buildList(wrong);
}
print(html);
1 Answer
Steven Parker
243,656 PointsYou're adding to (with the "+=" operator) the "html" variable before it has any contents, and this causes "undefined' to be shown first.
You can fix it by either initializing it with an empty string (var html = "";), or you could make the very first assignment a plain assignment ("=") instead of an addition assignment ("+=").
SAMUEL LAWRENCE
Courses Plus Student 8,447 PointsSAMUEL LAWRENCE
Courses Plus Student 8,447 Pointsahhhhhhhhhh! Thanks man.