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 trialMargaret Godowns
6,268 PointsJS Error "Uncaught TypeError: Cannot read property '0' of undefined" - Someone please tell me what is incorrect.
I'm working on the quiz challenge in Stage 2 of Loops, Arrays and Objects, and my code looks exactly like the example (unless I'm missing something). When I run the program, I get the error "Uncaught TypeError: Cannot read property '0' of undefined" in my console" on js line 18. I don't see anything wrong with line 18. Does anyone else?
var quiz = [
["What year is it?", 2015],
["How old are you?", 24],
["How many days are in February usually?", 28]
]
var question;
var answer;
var response;
var correctAnswers = 0;
var html;
function print(message) {
document.write(message);
}
for (var i = 0; i <= quiz.length; i += 1) {
question = quiz[i][0];
answer = quiz[i][1];
response = parseInt(prompt(question));
if (answer === response) {
correctAnswers += 1;
}
}
html = "You got " + correctAnswers + " right.";
print(html);
1 Answer
Colin Bell
29,679 PointsIn your for loop, it needs to be i < quiz.length
.
There are 3 items in the quiz array, so the length is 3. However, since array index starts at 0, the final array index will always be one fewer than its length - in this case the last index being 2. Since there isn't a quiz[3], there is no [0] property for a non-existent item and that's why it's returning an error.
for (var i = 0; i < quiz.length; i += 1) {
// ^ Here
question = quiz[i][0];
answer = quiz[i][1];
response = parseInt(prompt(question));
if (answer === response) {
correctAnswers += 1;
}
}
Margaret Godowns
6,268 PointsMargaret Godowns
6,268 PointsColin thank you so much you're the best!