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.
Math.sign(42); // 1 Math.sign(-0.1); // -1 Math.sign(0); // 0
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 likeMath.sign(x) === 1or use> 0and< 0tests; do not assume a result is neverNaN. - Zero keeps its sign.
Math.sign(-0)returns-0, which===treats as equal to0. UseObject.is()if the difference matters. - Comparators:
Math.sign(a - b)is a valid sort comparator for numbers.a - balone also works for finite numbers. Both fail onNaNand onInfinity - Infinity. - Reassembling a value:
Math.sign(x) * Math.abs(x)equalsxfor 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 is0. - 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 returnsNaN.
Browser support
Math.sign() is available in all current browsers and runtimes. It was added in ES2015, so Internet Explorer did not support it.
Related
Math.abs(),Math.trunc(),Math.round(),Math.max()- Lessons: Math, Numbers