Q:

Javascript memory game puzzle

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

A:

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

