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 trialRoman Opalacz
2,975 PointsCan't figure out why my code is printing 'undefined' along side my desired output
So my code seems to be functioning mostly correct but when I run it, in addition to my list of correct and incorrect answers, it also prints the text 'Undefined' at the start. I'm not sure what is triggering this output.
var quiz = [ ['How many moons does earth have?', '1'], ['What is my favorite color?', 'blue'], ['Where do I work?', 'HM'] ];
var correct = 0; var Incorrect = 0; var right = []; var wrong = []; var HTML;
function printList(list) { var listHTML = '<ol>'; for (var i = 0; i < list.length ; i +=1) { listHTML += '<li>' + list[i] + '</li>'; } listHTML += '</ol>'; return listHTML; }
function print(message) { document.write(message); }
for (var i = 0; i < quiz.length; i +=1) { var answer = prompt(quiz[i][0]); parseInt(answer); if (answer.toLowerCase() === quiz[i][1].toLowerCase()) { alert('Correct!'); correct += 1; right.push(quiz[i][0]); } else { alert('Incorrect :['); Incorrect +=1; wrong.push(quiz[i][0]); } }
HTML += 'You got ' + correct + ' questions correct.'; HTML += '<h2>You got these questions right</h2>'; HTML += printList(right); HTML += '<h2>You got these questions wrong</h2>'; HTML += printList(wrong); print(HTML);
1 Answer
KRIS NIKOLAISEN
54,972 PointsYou have declared the HTML variable without a value so the initial value is undefined. The += operator used later in your code then appends to this initial value. One fix would be to declare HTML with an empty string: var HTML = "";