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 Solution

Simpler solution, why not rendering?

So this is my solution which seems to not be outputting the number correct.

var quiz = [
  ['What color are Gala apples?', 'Red'],
  ['What brand of phone do Koreans make?', 'Samsung'],
  ['What type of bird is a Macaw?', 'Parrot']
];

var numCorrect = 0;
var question;
var answer;

for ( var i = 0; i <= quiz.length; i += 1 ) {
  var question = prompt(quiz[i][0]); /* response becomes new question value */
  var answer = quiz[i][1];
  if ( question === answer ) {
    numCorrect += 1;
  }
}

document.write('You have answered ' + numCorrect + ' questions correct.');

In this example, instead of having a variable called 'response' I transferred the user response value over to that specific question and made a conditional based on that ( question ==== answer).

Can anybody tell me why the console is telling me that 'quiz[i]' is undefined?

1 Answer

Your for condition should look like this :

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

It took me some time to figure it out.

awesome, I'm happy to find out that was all I needed!! Thanks for pointing that out to me.

I'm curious why it still wouldn't work though, especially since less than (<) occurs before equal to (=) ?

The quiz array got 3 elements in it but the 3 elements = quiz[0], quiz[1], quiz[2]. When you use the

  <=

It will try to search for a quiz[3] (because quiz.length = 3) but this one is undefined because it doesn't exist.

Is it clear ? It's pretty hard for me to explain this in english.

Yeah I understand it, thanks. I am confusing the 'length' of var quiz (3) with the 'index position' of the last array (2). Since the loop executes on quiz[0], the program was looking for a forth array aka quiz[3].

quiz[0]
1 <= 3 (true)
quiz[1]
2 <= 3 (true)
quiz[2]
3 <= 3 (true)
quiz[3] ?undefined?
4 <= 3 (false)

Yes this is it, it begins with 0 and quiz[3] doesn't exist so the console returns undefined.