3

I want to check the following

1: Is x a number
2. If x is less that 5 or greater than 15, sound alert 3. If all is ok, callMe()

var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}

What am I doing wrong?

0

3 Answers 3

4
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
    alert('not allowed')
}
else
{
    callMe();
}

This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.

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

2 Comments

Simple and correct. When x is not a number, the first condition is True and it won't check further comparison conditions.
@Naomi: To explain your code: Your condition was that x is not a number and it should be smaller than 5 or greater then 15. But how can NaN be smaller or bigger than a number?
2

All the other answers about the && vs || are correct, I just wanted to add another thing:

The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:

isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true

In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.

3 Comments

I did not try all browsers (and maybe browsers have changed the way they handle isNaN since your answer), but what you say is not correct in Chrome 34: jsfiddle.net/ss5ja
@GôTô - Interesting. I don't know whether I made a mistake 4 years ago, or things have indeed changed. Still, the behavior of the function can be odd in some other edge cases: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
Yeah... Not sure what is considered the best way to replace isNaN but it does not seem trustworthy indeed!
1
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
    alert('not allowed')
}
else
{
    callMe();
}

Comments

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.