How do I check if a value is a negative number in JavaScript?
Gable E
gable e profile pic

To check if a value is a negative number in JavaScript, you can use the following approaches: 1. Using the less than operator (<): - Compare the value with zero using the less than operator (<). - If the value is less than zero, it is a negative number.

1
2
3
4
5
6
7
8
9

   function isNegativeNumber(value) {
     return value < 0;
   }

   console.log(isNegativeNumber(-5)); // Output: true
   console.log(isNegativeNumber(0)); // Output: false
   console.log(isNegativeNumber(10)); // Output: false
   

In this example, theisNegativeNumber() function checks if the value is less than zero using the< operator. 2. Using the unary negation operator (-): - Apply the unary negation operator (-) to the value and check if the result is greater than zero. - If the result is greater than zero, the value is a negative number.

1
2
3
4
5
6
7
8
9

   function isNegativeNumber(value) {
     return -value > 0;
   }

   console.log(isNegativeNumber(-5)); // Output: true
   console.log(isNegativeNumber(0)); // Output: false
   console.log(isNegativeNumber(10)); // Output: false
   

In this example, theisNegativeNumber() function applies the unary negation operator to the value and checks if the result is greater than zero. It's important to note that both approaches assume the value is expected to be a numeric type (either a number or a string that represents a number). If the value can be of different types, you may need additional checks to ensure it is a valid number before performing the negative number check. Choose the approach that best fits your specific use case. The first approach with the less than operator (<) is commonly used and straightforward. The second approach with the unary negation operator (-) can be useful if you want to explicitly negate the value before performing the check.