Detecting if any type of JS object or literal represents a number is a bit tricky. This is because the most of the convertion methods treat falsy values as 0
, especially an empty string is converted to zero.
parseFloat
and parseInt
are execptional, they will return NaN
from any falsy value. However, they will pass a string with trailing non-number characters. Hence we've to detect both, falsy values and strings.
The only reliable way is the method in CMS'es wiki-answer @KevinB has linked in a comment, i.e.
if (!isNaN(parseFloat(n)) && isFinite(n)) {/* Passed, we've a number */}
Then there's another problem in your code, the recursive call if invalid values were entered. If you wanted to return for example a sum of x
and y
, num
would return a wrong value, if some invalid value(s) was/were entered before valid values. This problem won't occur in your particular code, but on the other hand, it also won't allow convertion of the variables to numbers in the correct stage either, hence you've to change the code anyway.
To fix the recursion issue, you've to check each prompt
separately:
var x, y;
while (!(!isNaN(parseFloat(x)) && isFinite(x))) {
x = prompt(...);
}
while (!(!isNaN(parseFloat(y)) && isFinite(y))) {
y = prompt(...);
}
Now x
and y
are representing valid numbers, so we can convert them:
x = +x;
y = +y;
After having all this done and seen it working, we'll see, that prompt
is actually an awful way to ask user for information. A better way would be a form with inputs and "Get relations" button.