let age = "";
while (age !== NaN) {
age = prompt("what is your age");
Number(age);
}
I can not leave the while loop although I write a number in the prompt box, why?
Mamun
69k9 gold badges51 silver badges62 bronze badges
1 Answer 1
You can use isNaN() function to determine whether a value is NaN or not. You have to add age == "" as part of the condition with || to pass for the initial value (empty string).
The condition should be:
while (isNaN(age) || age == "")
You also have to re-assign the converted value to the variable.
let age = "";
while (isNaN(age) || age === "") {
age = prompt("what is your age");
if(age == null)
break;
else
age = Number(age);
}
answered Dec 11, 2018 at 14:28
Mamun
69k9 gold badges51 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
H.A.A
let age = ""; while (isNaN(age) || age == "") { age = prompt("what is your age"); age = Number(age); } is a good solution. But whats is wrong with age === "" (with 3 equal signs). I leave the loop when I click Cancel or OK without writing. let age = ""; while (isNaN(age) || age === "") { age = prompt("what is your age"); age = Number(age); }
Mamun
@H.A.A, when cancel button is clicked age has null value, in that case you have to break the loop.....updated the answer....please check.
H.A.A
I got it. age = Number(age); changes the type of age to Number that is why age==="" does not work because empty "" is not a number.
H.A.A
The following code solved my problem: let age = ""; while (isNaN(age) || age == "") { age = prompt("what is your age"); age = Number(age); } let age = ""; while (isNaN(age) || age === "") { age = prompt("what is your age"); if(age == null) break; else age = Number(age); } leaves tho loop without asking the age again.
Mamun
@H.A.A, does my answer solve your question or you want some thing else?
|
lang-js
ageto a string, and the return value fromprompt()is also always a string, and no string is ever===toNaN. The call toNumber(age)has no effect; you probably wantage = Number(age);.