JavaScript Math.sign() Method



The JavaScript Math.sign() method accepts a numeric value as a parameter, computes the sign of the specified number and returns the result.

Following are the possible return values for the Math.sign() method −

  • If provided number is positive, returns 1.
  • If provided number is negative, returns -1.
  • If number is positive zero, returns 0.
  • If number is positive zero, returns -0.
  • If provided number is non-numeric, returns "NaN".

Syntax

Following is the syntax of JavaScript Math.sign() method −

Math.sign(x);

Parameters

This method accepts only one parameter. The same is described below −

  • x: The number for which we want to determine the sign.

Return value

This method returns whether the specified number is negative, positive or zero.

Example 1

In the following example, we are using the JavaScript Math.sign() method to check the sign of the provided number −

<html>
<body>
<script>
   const positiveNumber = 7;
   const sign = Math.sign(positiveNumber);
   document.write(sign);
</script>
</body>
</html>

Output

The above program returns "1" as the provided number is a postive integer.

Example 2

Here, we are passing negative integer to the Math.sign() method −

<html>
<body>
<script>
   const negativeNumber = -5;
   const sign = Math.sign(negativeNumber);
   document.write(sign);
</script>
</body>
</html>

Output

If we execute the above program, it returns "-1" as result.

Example 3

If the provided number is 0, this method returns "0" as result −

<html>
<body>
<script>
   const zero = 0;
   const sign = Math.sign(zero);
   document.write(sign);
</script>
</body>
</html>

Output

As we can see in the output, it returns 0.

Example 4

If we provide a non-numeric argument to this method, it returns "NaN" as result −

<html>
<body>
<script>
   const nonNumeric = "Tutorialspoint";
   const sign = Math.sign(nonNumeric);
   document.write(sign);
</script>
</body>
</html>

Output

As we can see in the output, it returns "NaN".