38

How to check if the value is not greater than 0 in javascript?

I tried

if(!a>0){}

But it's not working.

Ismail
  • 8,904
  • 3
  • 21
  • 39
fc123
  • 898
  • 3
  • 16
  • 40

4 Answers4

99

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
  • 297,002
  • 52
  • 306
  • 350
  • 4
    Note that the two `if` statements are only the same if `a` is a number. `tempStr = "asdasdasd"; !(tempStr > 0) // true; tempStr <= 0 // false;` – dayuloli Oct 31 '15 at 08:28
  • 20
    @Mureinik: `!(>)` isn't the same as `<=` if `a` is null/undefined. – Devin Burke Nov 07 '16 at 00:12
  • In addition to what @Devin Burke said, !(>) also checks that the value is a number whereas <= does not. !(>) seems superior to me. – ryanmc Sep 13 '21 at 14:14
16

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.

Ben Green
  • 161
  • 1
  • 3
  • 2
    Great answer. Only: `true > 0` or (`true > false`) actually yields `true` in JavaScript so your last statement (“they can't be greater or less than”) is wrong. – Raphael Schweikert Jan 03 '15 at 13:51
4

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

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)
jjk_charles
  • 1,250
  • 11
  • 23