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 trialBrendan Moran
14,052 PointsMy quiz with one small improvement (prevent hanging/empty category)
After I adjusted my code to Dave's specs from what I had before (I had it working, albeit in a more complicated way, using nodes both lists and their headlines), I noticed room for one small improvement: preventing an empty category just in case no questions are answered wrong or no questions are answered right. Towards the bottom of the code, I entered a single-line comment about it.
var answersCorrect = 0;
var question;
var answer;
var response;
var html;
var rightAnswers = [];
var wrongAnswers = [];
var questions = [
['What is the capitol of Rhode Island?', 'Providence'],
['What is your cat\'s name?', 'Baxter'],
['Who is Superman?', 'Clark Kent']
];
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function printList(arr) {
var listHTML = "<ul>";
for (var i = 0; i < arr.length; i += 1) {
listHTML += "<li>" + arr[i] + "</li>";
}
listHTML += "</ul>";
return listHTML;
}
for (i = 0; i < 3; i += 1) {
question = questions[i][0];
answer = questions[i][1];
response = prompt(question);
if (response.toLowerCase() === answer.toLowerCase()) {
answersCorrect += 1;
rightAnswers.push(question);
} else {
wrongAnswers.push(question);
}
}
html = 'You got ' + answersCorrect + ' right.';
if (rightAnswers.length > 0) { // If statement to prevent empty category in case of no answers right or no answers wrong
html += "<h2>You got the following questions right:";
html += printList(rightAnswers);
}
if (wrongAnswers.length > 0) {
html += "<h2>You got the following questions wrong:";
html += printList (wrongAnswers);
}
print(html);