tags:

views:

26

answers:

4

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?

+2  A: 
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.

GôTô
Simple and correct. When `x` is not a number, the first condition is True and it won't check further comparison conditions.
eumiro
spot on..thanks!
Naomi
You're welcome :)
GôTô
@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?
Felix Kling
A: 

in your example> isNaN returns false for x=10, thus else branch is used and callMe() is called. is this right?

Jan Turoň
A: 
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
    alert('not allowed')
}
else
{
    callMe();
}
spender
thanks for the solution
Naomi
+1  A: 

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.

Vilx-