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 Basics (Retired) Making Decisions with Conditional Statements The Conditional Challenge

Can a variable === a variable?

Why doesn't this add one to the correctAnswer variable?

var correctAnswer = 0;
var answer1 = 2;
var guess1 = prompt("What is 1 + 1?");
if (guess1 === answer1){
  correctAnswer += 1;
}
document.write(correctAnswer);

this works if I write

if(guess1 === 2)

...but shouldn't it also work the other way? I am missing something. Any help would really be appreciated.

Anytime. Enjoy the journey!

1 Answer

Three equal signs like you have will compare the value and type. So you are comparing an integer (the answer) to a string (the guess). Two equal signs will only compare the value which is what you'll want to use here.

In-depth learning: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons

Thanks Jeff. I appreciate your help. The stackoverflow resource helpful as well. Is the "guess", which in this case is the response to the prompt("What is 1 + 1?"), always a string?

It doesn't have to be a string. You can use parseInt() to turn the value into an integer before you run it through your if statement.

Resource: http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript

var correctAnswer = 0;
    answer1 = 2;
    guess1 = prompt("What is 1 + 1?");
    guess1 = parseInt(guess1);

if (guess1 === answer1){
  correctAnswer += 1;
}
document.write(correctAnswer);

Alright, thanks. I tried the parseInt(guess1) but made the mistake of putting it inside the if statement. This is very helpful. I appreciate your advice.

Anytime. Enjoy the journey!