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

If.. Else Statement not executing correctly. Simple Quiz.

var correct = 0; var wrong = 0; var questions = [ ["How many months are there in a year?", 12 ], ["What is my favorite vacation spot?", "Costa Rica"], ["How old am I?", 23] ];

for(var i = 0; i < questions.length; i ++ ) { prompt(questions[i][0]); }
if (questions[0][1] === 12 ) { print("Correct!"); correct += 1; } else { wrong += 1; }

if(questions[1][1] === "Costa Rica") { print("Correct!"); correct += 1; } else { wrong += 1; }

if(questions[2][1] === 23) { print("Correct!"); correct += 1; } else { wrong += 1; }

print(wrong);

While I was testing the code out I realized even if I put the wrong answer the code is still executing as correct. I tried with removing the correct answer from the array, but I don't think that is the issue.

https://w.trhou.se/0izcsexmvs

1 Answer

Steven Parker
Steven Parker
243,318 Points

When you issue the prompts, you are not saving the user response anywhere. Then, when do the tests for correctness, you are comparing the correct answer stored in the array with another copy of the correct answer, so it always matches.

While fixing this, you might also want to do the checks inside the loop so you can give feedback before asking the next question. That would also allow you to have a single variable for the response which you could re-use.