Check if a Number is a Negative Integer in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 17 20212 min read

banner

Photo by Tim Bogdanov

Check if a Number is a Negative Integer #

To check if a number is a negative integer:

  1. Pass the number to the Number.isInteger() method. The method returns true if the provided value is an integer and false otherwise.
  2. Check that the number is less than 0.
  3. If both conditions are met, the number is a negative integer.
index.js
function isNegativeInteger(value) { if (Number.isInteger(value) && value < 0) { return true; } return false; } console.log(isNegativeInteger(0)); // ๐Ÿ‘‰๏ธ false console.log(isNegativeInteger(-1.5)); // ๐Ÿ‘‰๏ธ false console.log(isNegativeInteger(-1)); // ๐Ÿ‘‰๏ธ true console.log(isNegativeInteger('-1')); // false

We used the Number.isInteger method to determine if the passed in value is an integer or not.

The method returns true if the value is an integer and false otherwise.

Here are some examples of using the Number.isInteger method directly.

index.js
console.log(Number.isInteger(3)); // ๐Ÿ‘‰๏ธ true console.log(Number.isInteger(3.5)); // ๐Ÿ‘‰๏ธ false console.log(Number.isInteger('3')); // ๐Ÿ‘‰๏ธ false console.log(Number.isInteger(-3)); // ๐Ÿ‘‰๏ธ true

We then used the logical AND (&&) operator to chain another condition.

For the if block to run both conditions have to be met.

The second condition is only evaluated if the first condition returns true.

In our second condition, we check if the integer is less than 0. If the value is an integer and it's less than 0, then it's a negative integer.

However, there is a caveat with the Number.isInteger method. The method returns true if the passed in value:

  • is an integer
  • is a float, that can be represented as an integer

Here are examples of floats that can be represented as integers:

index.js
// ๐Ÿ‘‡๏ธ true console.log(Number.isInteger(-5.0)); // ๐Ÿ‘‡๏ธ true console.log(Number.isInteger(-5.0000000000000000123));

It depends on your use case, however most applications are ok with considering numbers such as -5.0 and -3.0 to be negative integers.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee