JavaScript Reference ยท Math
Math.abs() method
Reference for JavaScript Math.abs(): get the absolute value of a number, how it converts its argument, edge cases like -0, NaN and Infinity, and common uses.
Math.abs() returns the absolute value of a number: its distance from zero, without the sign. Math.abs(-5) and Math.abs(5) are both 5. It is the usual tool for measuring a difference when you do not care which value is larger.
It is a static method of the Math object, so you always call it as Math.abs(x). You never create a Math object.
Math.abs(-7.25); // 7.25 Math.abs(3); // 3
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.abs(x)
| Name | Description |
|---|---|
x |
The value. It is converted to a number first, so numeric strings work. |
Return value: the absolute value of x, a non-negative number. The result is NaN if x cannot be converted to a number (including no argument or undefined), Infinity for Infinity and -Infinity, and 0 for -0.
Exceptions: a TypeError if x is a BigInt or a Symbol.
Usage notes
- Coercion is silent.
Math.abs("-8")is8,Math.abs(null)andMath.abs("")are0, andMath.abs("abc")isNaN. Validate input withNumber.isFinite()when you need to reject odd values. - Negative zero becomes positive zero. That can matter if you later use
Object.is()or1 / x. - It does not mutate anything. The method returns a new number.
- Use it for differences and tolerances:
Math.abs(a - b) < toleranceis the standard way to compare floating-point results (see floating-point numbers). - The most negative integers are fine. Numbers are doubles, so there is no overflow like with
abs(INT_MIN)in C. - BigInt:
Math.abs(-5n)throws. Writen < 0n ? -n : n. - Absolute value is not rounding. Combine it with
Math.round()orMath.trunc()when you also need whole numbers. - To keep the sign information, pair it with
Math.sign():Math.sign(x) * Math.abs(x)rebuildsx.
Browser support
Math.abs() is available in every browser and JavaScript runtime.
Related
Math.sign(),Math.trunc(),Math.max(),Math.hypot()- Lessons: Math, Numbers