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
Jeff Borg
4,302 PointsWhy is my statement never true?
Below is my code for one of the quizs. I have the console outputting the variables, and this is the console output I get.
From everything I can see, the vaules match, and the condition should be true.
answer variable is 4, and questions[i][1] is also 4 ...
======Console Output======
questions.length = 3
quiz.js:17
quiz.js:21 What is 2 x 2?
quiz.js:24 answer = 4 | QuestionA = 4
quiz.js:30 Wrong
quiz.js:31
quiz.js:21 What is 2 x 3?
quiz.js:24 answer = 7 | QuestionA = 6
quiz.js:30 Wrong
quiz.js:31
quiz.js:21 What is 2 x 4?
quiz.js:24 answer = 8 | QuestionA = 8
quiz.js:30 Wrong
=========================
========My Code==========
var questions = [
["What is 2 x 2?", 4],
["What is 2 x 3?", 6],
["What is 2 x 4?", 8]
];
console.log("questions.length = "+questions.length)
console.log(" ")
for (var i = 0; i < questions.length; i ++) {
console.log(questions[i][0]);
var answer = prompt(questions[i][0]);
console.log("answer = " + answer + " | QuestionA = " + questions[i][1])
if (answer === questions[i][1]) {
console.log("Correct");
console.log(" ")
} else {
console.log("Wrong");
console.log(" ")
}
}
function print(message) {
document.write(message);
}
=========================
2 Answers
Steven Parker
244,190 Points
It looks like you're trying to compare a number to a string.
The easiest solution is probably to store your answers as strings, like this:
["What is 2 x 2?", "4"], // <-- note: "4" is a string
Jeff Borg
4,302 PointsThanks for th comment, that put me in the right direction.
The input answer was a string, not an integer.
Thus, I changed:
if (answer === questions[i][1]) {
to
if (parseInt(answer) === questions[i][1]) {
and viola!
Thanks again.