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

General Discussion

Trevor Maltbie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Trevor Maltbie
Full Stack JavaScript Techdegree Graduate 17,021 Points

Correct/Wrong Arrays Print As Undefined

Previewing this code gets everything right except the correct and incorrect arrays print as ":undefined" and "undefined" respectively.

I tried using template literals around buildList but that didn't fix anything. I also tried removing the initial declaration of the html variable as Dave did but again that did not fix anything. I'm at a loss. There must be a typo somewhere.

const quiz = [
  ['How many moons does Earth have?', 1],
  ['How many eyes does a spider have?', 8],
  ['How many states in USA?', 50]
];
let correct = 0;
let question;
let answer;
let response;
let correctArray = [];
let wrongArray = [];
let html;

function print(message) {
  const outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

function buildList(arr) {
 let listHTML = '<ol>';
  for (let i=0; i < arr.length; i++) {
    listHTML += `<li> ${arr[i]} </li>`;
  }
  listHTML += '</ol>';
}

for(i=0; i<quiz.length; i++) {
  question = quiz[i][0];
  answer = quiz[i][1];
  response = parseInt(prompt(question));
  if (response === answer) {
    correct++;
    correctArray.push(question);
  } else {
    wrongArray.push(question);
  }
};

html = `You got ${correct} answers right.`;
html += '<h2>You got these questions correct:</h2>:';
html += buildList(correctArray);
html += '<h2>You got these questions incorrect:</h2>';
html += buildList(wrongArray);

console.log(correctArray); // this test was successful, console shows the correct questions. 
// still get undefined in the DOM though.
print(html); 
Steven Parker
Steven Parker
231,269 Points

I think you meant to post this in the "JavaScript" category. You can change it using "Edit Question", which is revealed by clicking on the small grey rectangle with the 3 dots in it.