How do I check if a value is a negative integer in JavaScript?
Antek N
antek n profile pic

To check if a value is a negative integer in JavaScript, you can use the following approach: 1. First, check if the value is a number: Use thetypeof operator to check if the value is of type"number". This ensures that the value is numeric before further validation. 2. Then, check if the value is an integer: Use theNumber.isInteger() method to check if the value is an integer. This method returnstrue if the value is an integer, andfalse otherwise. 3. Finally, check if the value is negative: Use a simple comparison operator (<) to check if the value is less than zero. This indicates that the value is negative. Here's an example function that performs the above checks:

1
2
3
4
5
6
7
8
9
10
11
12
13

function isNegativeInteger(value) {
  if (typeof value === "number" && Number.isInteger(value) && value < 0) {
    return true;
  }
  return false;
}

// Usage example:
console.log(isNegativeInteger(-5)); // Output: true
console.log(isNegativeInteger(10)); // Output: false
console.log(isNegativeInteger(0)); // Output: false
console.log(isNegativeInteger("abc")); // Output: false

In the example above, theisNegativeInteger() function takes avalue as an argument and checks if it is a negative integer. It first checks if the value is of type"number" using thetypeof operator. Then, it verifies if the value is an integer usingNumber.isInteger(). Finally, it checks if the value is less than zero to determine if it is negative. By combining these checks, the function accurately determines if a value is a negative integer. It returnstrue if the value satisfies all the conditions, andfalse otherwise. Note that the function handles non-numeric values gracefully, returningfalse for non-numeric inputs.