How do I check if a value is a positive or negative number in JavaScript?
Ava W
ava w profile pic

In JavaScript, you can check if a value is a positive or negative number using various methods. Here are a few approaches: 1. Comparison Operators: - You can use comparison operators (>,<,>=,<=) to check if a number is positive or negative.

1
2
3
4
5

   const number = 42;
   const isPositive = number > 0;
   const isNegative = number < 0;
   

In this example,number > 0 checks ifnumber is greater than 0, indicating that it is a positive number, andnumber < 0 checks ifnumber is less than 0, indicating that it is a negative number. 2. Math.sign(): - TheMath.sign() method returns the sign of a number, indicating whether it is positive, negative, or zero. - It returns: --1 if the number is negative, -0 if the number is zero, and -1 if the number is positive.

1
2
3
4
5
6

   const number = -42;
   const sign = Math.sign(number);
   const isPositive = sign === 1;
   const isNegative = sign === -1;
   

In this example,Math.sign(number) returns-1 becausenumber is negative. Then, you can check ifsign is equal to1 for positive numbers and-1 for negative numbers. 3. isNaN() and isFinite(): - To handle cases where the value may not be a number, you can combine theisNaN() andisFinite() functions with comparison operators.

1
2
3
4
5

   const value = '42';
   const isPositive = Number(value) > 0 && isFinite(value);
   const isNegative = Number(value) < 0 && isFinite(value);
   

In this example,Number(value) convertsvalue to a number, andisFinite(value) checks if the converted value is a finite number. The comparison operators then determine if the number is positive or negative. Choose the method that best fits your use case and consider the specific requirements of your application. It's important to handle potential edge cases and ensure that the value being checked is indeed a number before performing comparisons.