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

Quiz part works, but final message does not display

When I run my code, I am prompted for each question and the program correctly tells me whether my answer was right or not.

However, the console is reporting the following error; plus, the final message -- print(html) -- is not displaying.

Uncaught TypeError: Cannot read property '0' of undefined(anonymous function) @ quiz.js:17

Can somebody help me debug this?

var score = 0;
var response;
var html;

var questions = [
  ["What is the capital of New York State?", "albany"],
  ["What is the capital of Washington State?", "olympia"],
  ["What is the capital of California?", "sacremento"]
];    

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

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

  response = prompt(questions[i][0]);

  if (response.toLowerCase() === questions[i][1]) {
    score +=1;
    alert("That's correct!");

  } else {
    alert("No, sorry. That's incorrect.");
  }

}

html = "You scored " + score + " points.";
print(html); 

1 Answer

The variable questions is undefined because the for loop is running one extra time after it has looped through all the array index's.

// i = 3; i <= 3  true 

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

  response = prompt(questions[i][0]);

  if (response.toLowerCase() === questions[i][1]) {
    score +=1;
    alert("That's correct!");

  } else {
    alert("No, sorry. That's incorrect.");
  }

}