Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript memory game puzzle

Tags:

javascript

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

like image 232
WTFreezer Avatar asked May 01 '26 07:05

WTFreezer


2 Answers

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 ===

like image 87
Matt Burland Avatar answered May 02 '26 20:05

Matt Burland


=== 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/

like image 38
Yuriy Galanter Avatar answered May 02 '26 20:05

Yuriy Galanter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!