Search code examples
javascriptprompt

How to distinguish between null and empty string in prompt window?


I have to check (prompt window is obligatory) if a user entered a correct answer on these conditions:

  1. If a user entered a correct answer, alert 'you are correct'.
  2. If a user enters a wrong answer OR leaves it EMPTY, alert 'you are wrong' 3 If a user presses the cancel button nothing happens.
    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?


Solution

  • 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".

    • Don't parseInt before you start your tests.
    • Test for null before you test for !== result.
    • Test for userInput === parseInt(result, 10) (always use a radix with parseInt)