Check if Number is not Greater than 0 in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 27, 2022

banner

Photo from Unsplash

Check if Number is not Greater than 0 #

To check if a number is not greater than 0, use the logical NOT (!) operator to negate the condition, e.g. !(num > 0). If the number is not greater than 0, the condition will return true, otherwise false is returned.

index.js
const num = -5; if (!(num > 0)) { console.log('✅ number is not greater than 0'); } else { console.log('⛔️ number is greater than 0'); }

We used the logical NOT (!) operator to negate the greater than sign.

Note that we had to wrap the condition in parentheses. Had we not done that, we would have used the logical NOT (!) operator to negate the value of the num variable.

An alternative and more common approach is to use the less than or equals to sign.

To check if a number is not greater than 0, check if the number is less than or equal to 0, e.g. num <= 0. If the condition returns true, the number is not greater than 0.

index.js
const num = -5; if (num <= 0) { console.log('✅ number is not greater than 0'); } else { console.log('⛔️ number is greater than 0'); }

This code snippet achieves the same result. However, it is a bit more intuitive and more commonly used.

If the number is less than or equal to 0, then we know that it's not greater than 0.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.