Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1

Charles McKelvey
Charles McKelvey
2,276 Points

My string answers work but my numeric answers come up wrong when typed correctly, what's happening?

var correct = 0; var incorrect = 0;

var QnA = [ ['What is the color of the sky?', 'blue'], ['How many states are there in the United States of America?', 50], ['What is four multiplied by four?', 16] ];

for (var i = 0; i <= 2; i++) { var ans = prompt(QnA[i][0]); if (ans === QnA[i][1]) { correct++; } else { incorrect++; } if (i === 2) { document.write('You got ' + correct + ' question(s) right.<br>'); document.write('You got ' + incorrect + ' question(s) wrong.'); } }


So the first question with the answer blue works but when doing the 50 and 16, it comes up as wrong. I changed the first answer to 4 and then that started coming up wrong but then I changed 50 and 16 to fifty and sixteen and it started working. I don't understand why strings are allowed yet numbers aren't being communicated properly. I've been looking at this for awhile so maybe I'm missing something.

1 Answer

Prompt returns a string (ans will always be a string) so ans === QnA[i][1] is strictly comparing a string to a number and returning false because the types don't match.

Change it to ans == QnA[i][1] and it should work.