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 Solution

Quiz returning NaN values

Hi, after I've put all my code in and previewed my webpage, my lists print NaN instead of the list of questions. I have combed through my code and cant figure out where the error is. Does anyone see what Im doing wrong?

Heres the JS, thanks!

var quiz = [
  ['How tall is David?', 6],
  ['What is the meaning of life?', 42],
  ['How many fingers are there on one human hand?', 5]

];
var correctAnswers  = 0;
var question;
var answer;
var response;
var html;
var correct = [];
var wrong = [];

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

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

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

}



html = "You got " + correctAnswers + " questions correct!";
html +=  '<h2>You got these questions correct:</h2>';
html += buildList(correct);
html += '<h2>You got these question incorrect:</h2>';
html += buildList(wrong);
print(html);

I don't know, if I console.log correct and wrong it logs correctly, so what does that mean? They are getting into the arrays, somethings not coming out of the function correctly? I'll have another look.

1 Answer

Steven Parker
Steven Parker
231,269 Points

:point_right: The buildList function contains this line:

    listHTML =+ '</ol>';

The monadic "+" operator is forcing numeric type coercion on a string which does not represent a number, producing NaN.

This is probably just a typo and the assignment was intended to be a string concatenation using "+=".

Steven to the rescue :D

Yup, total typo on my part! thank you!! and sorry for wasting your time :/