JavaScript Tutorial JavaScript References

JavaScript - Math.sign() Method



The JavaScript Math.sign() method returns the sign of the passed argument, indicating whether it is positive, negative, or zero.

Syntax

Math.sign(x)

Parameters

x Specify a value. If it is not a number, it is implicitly converted to one.

Return Value

Returns a number representing the sign of the given argument:

  • If the argument is positive, returns 1.
  • If the argument is negative, returns -1.
  • If the argument is positive zero, returns 0.
  • If the argument is negative zero, returns -0.
  • Otherwise, NaN is returned.

Example:

In the example below, Math.sign() method is used to return the sign of a given value.

var txt;

txt = "Math.sign(10) = " + Math.sign(10) + "<br>";
txt = txt + "Math.sign(-10) = " + Math.sign(-10) + "<br>";
txt = txt + "Math.sign(0) = " + Math.sign(0) + "<br>";
txt = txt + "Math.sign(-0) = " + Math.sign(-0) + "<br>";
txt = txt + "Math.sign('10') = " + Math.sign('10') + "<br>";
txt = txt + "Math.sign('-10') = " + Math.sign('-10') + "<br>";
txt = txt + "Math.sign('xyz') = " + Math.sign('xyz') + "<br>";

The output (value of txt) after running above script will be:

Math.sign(10) = 1
Math.sign(-10) = -1
Math.sign(0) = 0
Math.sign(-0) = 0
Math.sign('10') = 1
Math.sign('-10') = -1
Math.sign('xyz') = NaN

❮ JavaScript - Math Object