2
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?

1
  • You initialize age to a string, and the return value from prompt() is also always a string, and no string is ever === to NaN. The call to Number(age) has no effect; you probably want age = Number(age);. Commented Dec 11, 2018 at 14:24

1 Answer 1

4

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);
}

Sign up to request clarification or add additional context in comments.

6 Comments

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); }
@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.
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.
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.
@H.A.A, does my answer solve your question or you want some thing else?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.