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 trialJacob Jozefowicz
3,284 PointsTypeError: questionsAndAnswers[i] is undefined
I keep getting that error in the console.
function print(message) {
document.write(message);
}
function list(x) {
var listed = x.join(" - ");
return listed;
}
var correctAnswers = 0;
var questionsAndAnswers = [
["What is after 2?", "3"],
["Capital of Ireland?", "dublin"],
["Write 3 in word form", "three"]
];
for(var i = 0; i <= 3; i++)
{
var rightAnswer = questionsAndAnswers[i][1];
var userAnswer = prompt(questionsAndAnswers[i][0]);
questionsAndAnswers[i].push(userAnswer);
if(rightAnswer == userAnswer)
{
questionsAndAnswers[i].push("Correct");
correctAnswers++;
}
else
{
questionsAndAnswers[i].push("Wrong");
}
}
for( var i = 0; i <= 3; i++)
{
var stats = list(questionsAndAnswers[i]);
print(stats);
}
print(correctAnswers);
```
1 Answer
Nicholas Olsen
Front End Web Development Techdegree Student 19,342 PointsBoth of your for loops count from 0 to 3, they should count from 0 to 2.
Arrays start a 0, so if you have 3 elements in an array, you only count to 2 because "0, 1, 2" is three numbers total. So right now, your loop goes through 3 times as it should, but then on the 4th time it looks for questionsAndAnswers[3], which is undefined.
The solve this, just replace " i < = 3 " with " i < 3 " or " i < = 2 " in both for loops.
Most of the time people write "i < 3"
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsI would also suggest that you use
i < questionsAndAnswers.length
to make your program a little more dynamic.Currently you have 2 places that you have to remember to go back and change a number if you add or remove questions from your array.
Jacob Jozefowicz
3,284 PointsJacob Jozefowicz
3,284 PointsDamn it, I thought it might be a careless mistake like that. Thank you!