Why Is Typeof X Never 'number' When X Comes From The Prompt Function?
Solution 1:
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:
functionage_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;
}
functionconfirm_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();
Solution 2:
The other answers are showing you that prompt() (almost) always returns a string. You'll need to parseInt the response before you can check it for your age range. But I think your while-loop conditional is throwing you off. Also you need to parseInt() on the prompt a second time, inside your while loop. Try it like this:
let age_entered = prompt("Enter Your Age:");
age_entered = parseInt(age_entered);
while (age_entered <= 0 || Number.isNaN(age_entered)) {
alert("You entered an incorrect value. Please enter correct age.");
age_entered = prompt("Enter Your Age:");
// do parseInt again
age_entered = parseInt(age_entered);
}
Notice we use Number.isNaN(age_entered). This is a more robust way to determine if a value is a number than comparing with typeof. See this doc here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
Solution 3:
prompt()
is always returning a string,
Try parseInt(prompt("Enter Your Age:"))
.
Solution 4:
It's returning a string, and parseInt will save you:
...
let age = parseInt(age_of_user());
...
Post a Comment for "Why Is Typeof X Never 'number' When X Comes From The Prompt Function?"