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 2

Brendan Moran
Brendan Moran
14,052 Points

Here's How I Tried It, How could I have done it better? Feedback welcome.

Everything works together with the HTML, the quiz executes fine as do all the printing functions. Just wondering how I could have approached this better. Did it with minimal searching around for answers, just trying to figure out a way to make it work.

var answersCorrect = 0;
var question;
var answer;
var response;

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(item) {
  var list = "";
  var rightHeadline = document.getElementById('right_title');
  var wrongHeadline = document.getElementById('wrong_title');
  var rightUL = document.getElementById('right_list');
  var wrongUL = document.getElementById('wrong_list');
  for (var i = 0; i < item.length; i += 1) {
    list += "<li>" + item[i] + "</li>"
  } if (item === rightAnswers) {
    rightHeadline.innerHTML = 'You got the following questions correct:'
    rightUL.innerHTML = list;
  } else {
    wrongHeadline.innerHTML= 'You got the following questions wrong:'
    wrongUL.innerHTML = list;
  }
}

for (i = 0; i < 3; i += 1) {
  question = questions[i][0];
  answer = questions[i][1];
  response = prompt(question);
  if (response === answer) {
    answersCorrect += 1;
    rightAnswers.push(questions[i][0]);
  } else {
    wrongAnswers.push(questions[i][0]);
  }
}

print('You got ' + answersCorrect + ' right.');
printList(rightAnswers);
printList(wrongAnswers);

1 Answer

Looks good! Only thing I see would be to make the for loop that generates the prompts use the length of the questions array, so you don't have to update it if you add more questions:

 for (i = 0; i < questions.length; i += 1) {

Also, it's not really making it better per se, but i += 1 can be shortened to i++

Brendan Moran
Brendan Moran
14,052 Points

Hey, good catch! Thanks.