Why is typeof x never ‘number’ when x comes from the prompt function?

As mentioned in the comments, the prompt() function always captures the input as a string, even when the input is a valid number. To check if it’s a number, you can try to parse the returned string with parseInt(age_entered) (or parseFloat if you want to allow non-integer ages, although that’d seem odd to me), and if you get back a number, the input is good – if you get back NaN, it wasn’t valid.

Here’s your script updated based on this understanding:

function age_of_user() {
    let age_entered = parseInt(prompt("Enter Your Age:")); 
    while (Number.isNaN(age_entered) || age_entered <= 0) {
       alert("You entered an incorrect value. Please enter correct age.");
       age_entered = parseInt(prompt("Enter Your Age:"));
    }   
return age_entered;
}

function confirm_age() {
    let age = age_of_user();
    if (age < 18) {
        alert("Sorry! You need to be an adult to view content.");
    }
    else {
        alert("Welcome to our site.");
    }
}

confirm_age();

Leave a Comment