I have to check (prompt window is obligatory) if a user entered a correct answer on these conditions:
var num1 = Math.floor(Math.random() * 9 + 1);
var num2 = Math.floor(Math.random() * 9 + 1);
var result = num1 * num2;
var userInput = parseInt(prompt('What is ' + num1 + ' * ' + num2 + ' ?'));
if (userInput === result){
alert('You are correct!');
} else if (userInput === '' || userInput !== result) {
alert('You are wrong!');
} else if (userInput === null) {
alert('Cancelled!');
}
What happens is that alert says 'you are wrong' even if I press cancel. I added cancelled alert just for an example. Any suggestions?
You have two problems.
First, you are running the return value of prompt
through parseInt
before you test to see if it is an empty string or null.
Then you aren't distinguishing between null and "not the result".
parseInt
before you start your tests.null
before you test for !== result
.userInput === parseInt(result, 10)
(always use a radix with parseInt
)