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

SeHyun Choi
SeHyun Choi
3,441 Points

Uncaught TypeError: Cannot read property '1' of undefined?

I am keep getting error message saying [1] is undefined. But in my 'questions array' I have 2, 4, 6.

CODE

var questions = [

    ["What is 1 + 1 = ?", 2],

    ["What is 2 + 2 = ?", 4],

    ["What is 3 + 3 = ?", 6],

];


var correctAnswers = 0;
var questions;
var answers;
var response;
var html;


function print(message) {
    var printIt = document.write(message);
    return printIt;
}



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

    questions = questions[i][0];

    answers = questions[i][1];

    response = parseInt(prompt(questions));

        if( response === answers ) {
            correctAnswer += 1;

        }
}

html = "You got" + correctAnswers + " question(s) right.";
print(html);

1 Answer

You have declared var questions twice and reassigned the variable here

questions = questions[i][0];

It would be better to use:

var question;
var answer;

and

question = questions[i][0];

You are also missing an s in correctAnswers here

correctAnswer += 1;