Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
Math.abs(-7.25);   // 7.25
Math.abs(3);       // 3

Try it

JS Absolute values

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

No output.

JS Coercion and a tolerance check

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

No output.

Syntax

JavaScript
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") is 8, Math.abs(null) and Math.abs("") are 0, and Math.abs("abc") is NaN. Validate input with Number.isFinite() when you need to reject odd values.
  • Negative zero becomes positive zero. That can matter if you later use Object.is() or 1 / x.
  • It does not mutate anything. The method returns a new number.
  • Use it for differences and tolerances: Math.abs(a - b) < tolerance is 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. Write n < 0n ? -n : n.
  • Absolute value is not rounding. Combine it with Math.round() or Math.trunc() when you also need whole numbers.
  • To keep the sign information, pair it with Math.sign(): Math.sign(x) * Math.abs(x) rebuilds x.

Browser support

Math.abs() is available in every browser and JavaScript runtime.