How to check if the value is not greater than 0
in javascript?
I tried
if(!a>0){}
But it's not working.
How to check if the value is not greater than 0
in javascript?
I tried
if(!a>0){}
But it's not working.
You need a second set of brackets:
if(!(a>0)){}
Or, better yet "not greater than" is the same as saying "less than or equal to":
if(a<=0){}
Mureinik's answer is completely correct, but seeing as "understanding falsey values" is one of the more important, less intuitive parts of JavaScript, it's perhaps worth explaining a little more.
Without the second set of brackets, the statement to be evaluated
!a>0
is actually evaluated as
(!a) > 0
So what does (!a) mean? It means, find the boolean truthiness of "a" and flip it; true becomes false and false becomes true. The boolean truthiness of "a" means - if a it have one of the values that is considered "false", then it is false. In all other instances, ie for all other possible values of "a", it is "true". The falsey values are:
false
0 (and -0)
"" (the empty string)
null
undefined
NaN (Not a Number - a value which looks like a number, but cannot be evaluated as one
So, if a has any of these values, it is false and !a is true If it has any other, it is true and therefore !a is false.
And then, we try to compare this to 0. And 0, as we know, can also be "false", so your comparison is either
if (true > false) {}
or
if (false > false) {}
Seeing as neither true or false can ever actually be anything other than equal to false (they can't be greater or less than!), your "if" will always fail, and the code inside the brackets will never be evaluated.
a <= 0
or (less clearly, IMO) !(a > 0)
The !
operator is being applied to a
, not the entire expression, so extra parentheses are necessary if you go the "not" route.
If you are hell-bent on using the >
symbol, just reverse the operators
if(0>a)
If a
can also be equal to 0
, then,
if(0>=a)