Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Math

Math.sign() method

Reference for JavaScript Math.sign(): find whether a number is positive, negative or zero, how it treats -0 and NaN, and practical uses in sorting and direction.

Math.sign() tells you the sign of a number. It returns 1 for a positive number, -1 for a negative number, and 0 or -0 for zero. If the argument is NaN, so is the result.

The method is useful in sorting comparators, in physics and animation code (which way is something moving?), and anywhere you want to apply a sign to another value.

JavaScript
Math.sign(42);    // 1
Math.sign(-0.1);  // -1
Math.sign(0);     // 0

Try it

JS The sign of values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Direction and comparators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Math.sign(x)
Name Description
x A number. Other values are converted to a number first.

Return value: 1 if x is positive (including Infinity), -1 if negative (including -Infinity), 0 for 0, -0 for -0, and NaN if x is NaN or cannot be converted.

Exceptions: a TypeError for a BigInt or a Symbol.

Usage notes

  • The result is one of five values (1, -1, 0, -0, NaN), not just three. Write comparisons like Math.sign(x) === 1 or use > 0 and < 0 tests; do not assume a result is never NaN.
  • Zero keeps its sign. Math.sign(-0) returns -0, which === treats as equal to 0. Use Object.is() if the difference matters.
  • Comparators: Math.sign(a - b) is a valid sort comparator for numbers. a - b alone also works for finite numbers. Both fail on NaN and on Infinity - Infinity.
  • Reassembling a value: Math.sign(x) * Math.abs(x) equals x for any finite number; use it to apply the sign of one number to the size of another.
  • Strings are coerced: Math.sign("-3") is -1; an empty string is 0.
  • BigInt: Math.sign(5n) throws. Compare directly: n > 0n ? 1n : n < 0n ? -1n : 0n.
  • Check the type first when input may not be numeric, because Math.sign("abc") simply returns NaN.

Browser support

Math.sign() is available in all current browsers and runtimes. It was added in ES2015, so Internet Explorer did not support it.