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

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.