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
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 ===
=== 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With