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

Vijayalaxmi vastrad
Vijayalaxmi vastrad
2,789 Points

I am getting "you got undefined question(s) right." can anyone tell me whats wrong in my code

var questions=[ ['how old are you?', 5], ['whats your name?', 'Jon'], ['how many litres of water do you drink in a day?', 4] ] var question; var response; var answer; var correctAnswer; var html; function print(message){ document.write(message); } for(var i=0;i<questions.length;i+=1){ question=questions[i][0]; answer=questions[i][1]; response=parseInt(prompt(questions)); if(response === answer){ correctAnswer += 1; } } html="you got "+ correctAnswer +" question(s) right."; print(html);

3 Answers

connor is right you have to set the value of correctAnswer to a number in this case to 0 and also there is a typo in your loop

for(var i=0;i<questions.length;i+=1){
  question=questions[i][0];
  answer=questions[i][1]; 
  response= parseInt(prompt(questions)); //here it should be (question) questions is actually the array
// here you are displaying the array not the questions
}

in this case this would work but when you try to parseInt() what the user types, and one of your answers is a string. so if you run this you will get 2 answers right even if you type the right answers. try using strings instead and remove the parseInt.

var questions=[
  ['how old are you?', '5'], // wrap numbers in quotation marks
  ['whats your name?', 'Jon'],
  ['how many litres of water do you drink in a day?', '4'] 
] ;

for(var i=0;i<questions.length;i+=1){
  question=questions[i][0];
  answer=questions[i][1]; 
  response= (prompt(question); // remove parseInt()
}

hope this helps

Connor Sayers
Connor Sayers
1,515 Points

You haven't assigned a value to correctAnswer to begin with. You want the code to += 1 to correctAnswer but it doesn't have a value to += 1 to.

Try: var correctAnswer = 0;

Let me know if this works!