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 1

I dont understand why i get this message.(quiz.js:14 Uncaught TypeError: Cannot read property '1' of undefined(…))

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

questions=[
['where do you live?','Madrid'],
['what is the color of the chair?','blue'],
['what car do you have?','none']
];
var solution=[];
var wrong=[];
for(var i=0;i<=3;i++){
 if( questions[i][1]==prompt(questions[i][0]))  {
   solution.push(questions[i][1]);
 }else wrong.push(questions[i][1]);
}
document.write('<p> You have solution.length </p>');

2 Answers

The problem is in your for loop. You have the conditional expression checking if i <= 3 but there are only three elements in your questions array which means that the elements are indexed as 0, 1, 2. There is no element with an index of 3 in your array so you are trying to access a record that isn't there when your i variable is equal to 3.

To fix this you need to change the expression to i < 3 (or i <= 2) or as a best practice you should compare it to the lenght of the questions[] array (questions.length) , so that if you add questions in the future the expression will still be valid.

In summary, the best way to write your for loop conditional is as follows:

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

O great, thank you Ted.