Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 2 Solution

Not sure why my code isn't working

I know I didn't do it exactly the way the teacher did it, but I would like to know why my code is generating random commas. Check it out here: https://jsfiddle.net/cameck/08zj03hd/

Everything works except there are random commas after the questions that get written to the page that I don't see noted anywhere. Maybe a new set of eyes will help?

1 Answer

Jason Desiderio
Jason Desiderio
21,811 Points

cameron eckelberry - you're getting commas after the question because you're printing out an array and the browser is trying to interpret that. You should initialize correctQs as a string: var carrectQs = ""; and concatenate the questions to the end of it like this: correctQs += '<li>' + questions[i][0] + '</li>';

You would do the same for wrongQs.

Here is the entire edited script:

var questions = [['What color is the Sky?', 'blue' ],
                ['Is it generally cloudy or sunny in Seattle?', 'cloudy'],
                ['At Subway do you eat fresh?', 'yes']];
var score = 0;
var html;
var answer;
var response;
var question;
var correctQs = "";
var wrongQs = "";
function print(message){
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}
for (i = 0; i < questions.length; i++){
  question = questions[i][0];
  answer = questions[i][1];
  response = prompt(question);
  if (answer === response) {
    score += 1;
    correctQs += '<li>' + questions[i][0] + '</li>';
  } else {
    wrongQs += '<li>' + questions[i][0] + '</li>';
  }
}
html = 'You got ' + score + ' question(s) right.<h2>You got these questions right:</h2><ol>' + correctQs + '</ol>' + '<h2>You got these questions wrong:</h2><ol>' + wrongQs + '</ol>';
print(html);

Thanks man, duh! I feel so dumb! :P