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