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

Code help please? (35 lines)

Hello,

Would appreciate some help on this:

Final result was this: "You got 1 correct answers. You got these questions right:

undefined What is 90 - 45? You got these questions wrong: undefined What is 2 + 2? What is 2 * 2?"

My code is

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

var questions = [
  ['What is 2 + 2?' , '4'],
  ['What is 2 * 2?' , '4'],
  ['What is 90 - 45?' , '45'],
    ];

var correct = [];
var wrong = [];
var questionData;
var questionMessage;
var questionAnswer;
var questionResponse;
var correctList;
var wrongList;

  for ( var i = 0 ; i < questions.length ; i += 1 ) {
   questionData = questions[i];
   questionAnswer = questionData[1];
   questionResponse = prompt(questionData[0]);
   if (questionResponse === questionAnswer) {
   correct.push(questionData[0]);
   correctList += "<li>" + questionData[0] + "</li>";
  } else {
   wrong.push(questionData[0]);
   wrongList += "<li>" + questionData[0] + "</li>";
  }
}

var html = "<h2> You got "  + correct.length + " correct answer(s).</h2> <p> You got these questions right: </p><ol>" + correctList + "</ol><h2> You got these questions wrong:</h2><ol>" + wrongList + "</ol>"

print(html);

Comments much appreciated :)

2 Answers

akak
akak
29,446 Points
var correctList;
console.log(correctList) // prints out 'undefined'

Variable declared like that starts with "undefined" value. If you overwrite it later with data it's not a big deal. But here you're just adding data to it by += so your adding to undefined. That's why you have undefined at the beginning of the sentence. Initialize it with an empty string like var correctList = "" instead.

Thank you for your help :)

Erik Nuber
Erik Nuber
20,629 Points

You are very close. You need to define your correctList and wrongList with no content

correctList = "";
wrongList = "";

This is why you are getting an undefined when you just add to the list itself.

You are saying += and when correctList is nothing to begin with it is considered undefined. So your correctList will hold

undefined + <li></li> + <li></li>

if two answers are correct.

Thank you for the answer! :)