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

Returns error when I use a number instead of .length

in my for loop, my question[x][0] within the prompt command would return an error when I put a x < 4 in the condition. However, when I replace the 4 with questions.length,, the program would run.

Could someone explain why this is the case? I can't understand why the question [x][0] and the questions.length depend on one another. Please see my code below:

/*ERROR FREE*/
for (var x = 0; x < questions.length; x += 1) {
  var answer = prompt(questions[x][0]);
  if (answer == questions[x][1]) {
   correct += 1;
} else {
   wrong += 1;
 }
}


/*ERROR*/

  for (var x = 0; x < 4; x += 1) {
  var answer = prompt(questions[x][0]);
  if (answer == questions[x][1]) {
   correct += 1;
} else {
   wrong += 1;
}
}

1 Answer

Steven Parker
Steven Parker
243,095 Points

Perhaps the questions array is too small?

You didn't show the part of the code where the questions array is established, but offhand I would guess that the reason the second example causes an error is that there are fewer than 4 items in the array.

To enable a complete and accurate analysis, always show the complete code or make a snapshot of your workspace and post the link to it.