JavaScript Math.sign() | Check if a number is positive, zero or negative

The JavaScript Math.sign() method is used when we need to check if a number is a positive, zero, or a negative number. This method returns 1 if specified number is a positive number. Otherwise returns 0 and -1 if specified number is zero or a negative number. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

  <p id="xyz"></p>

  <script>
    let num = -32;
    document.getElementById("xyz").innerHTML = Math.sign(num);
  </script>
   
</body>
</html>
Output

JavaScript Math.sign() Syntax

The syntax of Math.sign() method in JavaScript is:

Math.sign(x)

The parameter x refers to a number.

Please note: If specified x (a number as parameter to Math.sign()) is not a number, then NaN will be returned. Otherwise return 1, 0, or -1 if specified x is a positive, zero, or a negative number.

JavaScript Math.sign() Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

  <script>
    let myArray = [12, -34, 0, "fresherearth", 23.43];
    
    for(let i=0; i<myArray.length; i++)
    {
      if(Math.sign(myArray[i]) == 1)
        console.log(myArray[i] + " is a positive number.");
      else if(Math.sign(myArray[i]) == 0)
        console.log(myArray[i] + " is zero.");
      else if(Math.sign(myArray[i]) == -1)
        console.log(myArray[i] + " is a negative number.");
      else
        console.log(myArray[i] + " is not a number.");
    }
  </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by above JavaScript example:

javascript math sign example

JavaScript Online Test


« Previous Tutorial Next Tutorial »