Math.abs()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheMath.abs() static method returns the absolute value of a number.
In this article
Try it
function difference(a, b) { return Math.abs(a - b);}console.log(difference(3, 5));// Expected output: 2console.log(difference(5, 3));// Expected output: 2console.log(difference(1.23456, 7.89012));// Expected output: 6.6555599999999995Syntax
js
Math.abs(x)Parameters
xA number.
Return value
The absolute value ofx. Ifx is negative or-0, returns its opposite number-x (which is non-negative). Otherwise, returnsx itself. The result is therefore always a positive number or0.
Description
Becauseabs() is a static method ofMath, you always use it asMath.abs(), rather than as a method of aMath object you created (Math is not a constructor).
Examples
>Using Math.abs()
js
Math.abs(-Infinity); // InfinityMath.abs(-1); // 1Math.abs(-0); // 0Math.abs(0); // 0Math.abs(1); // 1Math.abs(Infinity); // InfinityCoercion of parameter
Math.abs()coerces its parameter to a number. Non-coercible values will becomeNaN, makingMath.abs() also returnNaN.
js
Math.abs("-1"); // 1Math.abs(-2); // 2Math.abs(null); // 0Math.abs(""); // 0Math.abs([]); // 0Math.abs([2]); // 2Math.abs([1, 2]); // NaNMath.abs({}); // NaNMath.abs("string"); // NaNMath.abs(); // NaNSpecifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-math.abs> |