3

I am coding a memory game that allows an alert to flash up with a 5-6 digit code that you have to then remember and place into a prompt box. Here is the code I have so far:

var mathRandom = (Math.round(Math.random()*10000))

alert(mathRandom);

var answer=prompt("What is the number?");
if(answer === mathRandom)
    {
        alert("Well done")
    }
    else
    {
        alert("Wrong")
    }

The problem with my code is that even when you get it right the alert says wrong, I think this is because when I am checking if the variables are equal the mathrandom generates a new number. I was wondering if I could have some help. Thanks

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
WTFreezer
  • 138
  • 7

3 Answers3

3

The problem is that answer is a string and mathRandom is a number. You are using === which doesn't coerce types. You need to convert your answer to a number and then compare:

if (+answer === mathRandom) {
    alert("Well Done");
}

Or:

if (parseInt(answer) === mathRandom) {
    alert("Well Done");
}

Or you could just use the == operator:

if (answer == mathRandom) {
    alert("Well Done");
}

Which will automatically convert the number in mathRandom to a string.

Also see this question: Which equals operator (== vs ===) should be used in JavaScript comparisons?

To better understand the difference between == and ===

Community
  • 1
  • 1
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

=== checks both the value and the type of the variable. Math functions generate number, while prompt generates string. This is why the variables are always unequal.

Replace that with == which checks only values - and your code will work.

Demo: http://jsfiddle.net/Bx7W8/

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

You need to convert the result of the prompt to a number. Right now you're doing a comparison with a string and a number.

In JavaScript:

750 !== "750";
750 === parseInt("750", 10);

Here's the fix:

var mathRandom = Math.round(Math.random() * 10000);

alert(mathRandom);

var answer = parseInt(prompt("What is the number?"), 10);
if (answer === mathRandom)
{
    alert("Well done")
}
else
{
    alert("Wrong")
}
David Sherret
  • 101,669
  • 28
  • 188
  • 178