Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Logical Operators in javascript

Tags:

javascript

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?

like image 315
Naomi Avatar asked Mar 24 '26 07:03

Naomi


2 Answers

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.

like image 162
GôTô Avatar answered Mar 25 '26 20:03

GôTô


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.

like image 21
Vilx- Avatar answered Mar 25 '26 21:03

Vilx-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!