Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not greater than 0 [closed]

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

I tried

if(!a>0){} 

But it's not working.

like image 747
fc123 Avatar asked Jan 03 '15 09:01

fc123


People also ask

Why we use === in JavaScript?

The === operator compares operands and returns true if both operands are of same data type and have some value, otherwise, it returns false. The !== operator compares operands and returns true if both operands are of different data types or are of the same data type but have different values.

What is == operator in JavaScript?

The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.

How do you negate in JavaScript?

The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .


2 Answers

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){} 
like image 102
Mureinik Avatar answered Oct 10 '22 06:10

Mureinik


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.

like image 23
Ben Green Avatar answered Oct 10 '22 04:10

Ben Green