Why is this while() loop coming up as an Infinite Loop?

87 views Asked by At

Just trying to figure out why the following code is an infinite loop?

var x = prompt("enter a number");

while (isNaN(x)){
    prompt("please enter a number");
}

All I wanted to do was to keep asking the user to enter a valid number until she does so.

2

There are 2 answers

0
T.J. Crowder On BEST ANSWER

Because you're not updating x within the loop:

var x = prompt("enter a number");

while (isNaN(x)){
    x = prompt("please enter a number"); // <====
}

Note that this is one of those places a do-while loop is useful:

var x;
do {
    x = prompt("please enter a number");
}
while (isNaN(x));

Also note that x will be a string. isNaN will work with it, though, because the first thing it does is try to convert its argument to a number if it's not one. But note that x remains a string and so (for instance) + may not do what you expect. So you might convert it using a unary +, Number(), parseInt, or parseFloat. (See this answer for details on those options.) Example:

var x;
do {
    x = +prompt("please enter a number");
//      ^
}
while (isNaN(x));
0
steenbergh On

On the first line of your script, you ask the user for input, and assign this input to x (Say that they enter 'a', not numeric). Then, you check to see if x is a number (it isn't). If it isn't a number, the user is asked for input again. However, that input is never (re- )assigned to x, and the value of x remains 'a'. the prompt-command is in no way coupled with the variable x. Try this within your loop

x = prompt("please enter a number");