It's because you use the strict equality operator ===
which also takes data types into consideration. The rand
value is a number, but the guess
value is a string. Therefor the two can never be equal even if the represented value is the same.
var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');
console.log(typeof rand);
console.log(typeof guess);
You could solve this by using the equality operator..
var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');
if (rand == guess)
console.log('correct');
else
console.log('false');
console.log(`correct number is : ${rand}`);
..changing the rand
number to a string..
var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');
if (rand.toString() === guess)
console.log('correct');
else
console.log('false');
console.log(`correct number is : ${rand}`);
..or by changing the guess
string to a number
var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');
if (rand === parseInt(guess, 10))
console.log('correct');
else
console.log('false');
console.log(`correct number is : ${rand}`);