﻿ Check if a given number is Negative or Positive in JavaScript – Math.sign()

Check if a given number is Negative or Positive in JavaScript – Math.sign()

There are two simple methods to check if a given number is negative or positive in JavaScript. The first method is using a comparison operator in JavaScript, the second method is using a new ES6 function called Math.sign().

Let’s see an example using both the methods.

1) Using Comparison Operator

<script>
const number = -5;

if (number < 0)
document.write (number + ' is negetive');
else
document.write (number + ' is positive');
</script>

In the above example, I am using the < (less than) operator to check if the number is either negative or positive.

Anybody can tell that the value is a negative number, just by looking at it, since I have assigned a negative value in the variable. However, you’ll need a condition like the one I have explained in the above example, when you are doing some big calculations and at runtime you need to check the value.

Now, guess what the above condition returns. Well, it returns a Boolean true or false. Do this to check…

<script>
const number = -5;
document.write (number < 0);
</script>

The output is true, since it’s a negative value.

2) Using Math.sign()

You can use the Math.sign() function in JavaScript, to check if a number is negative or positive. This new ES6 method takes an argument in the form of a number. Here’s the syntax.

Math.sign(number)

The function will return either of this …
1, -1, 0, -0, or NaN

The function returns the sign of the number (not any value). Therefore, if it’s a positive number, it will return 1 and if the number is negative, it will -1. If the value is zero it will return 0.

NaN denotes Not a Number, in case the parameter (or the argument) is not a number.

Note: The function is case sensitive.

Now, let's see how the function works.

<script>
const number = 17;

let result = Math.sign(number) > 0 ? ' is positive' : ' is negative';
document.write (number + result);
</script>
In the above example, I using the JavaScript Ternary (conditional) Operator to check the Math.sign() function's result for a given number.

Also, check the return type.

<script>
const number = 17;
document.write (Math.sign(number));
</script>

The output you should see is 1, that’s positive.

Difference between Comparison Operator and Math.sign() function

The difference between using the Comparison Operator and Math.sign() function is that the former returns a Boolean value (true or false) and later returns the sign of the number (-1 or 1).
Let's see both the methods together.

<script>
const number = -5;

document.write (number < 0);		 // if its less than 0.
document.write (Math.sign(number));
</script>

Examples using Math.sign()

Example
1. document.write (Math.sign()); Try it
2. const number = -5 - 10;
document.write (Math.sign(number));Try it
3. const number = -15 + 12;
document.write (Math.sign(number)); Try it