Math.abs()
abs(x) The Math.abs() function returns the absolute value of a number — the non-negative magnitude of the value regardless of sign. Positive numbers and zero are returned as-is; negative numbers are returned as their positive counterpart.
The function is useful any time you care about the size of a difference without caring about direction: checking whether two values are within a tolerance, computing distances, or normalizing signed measurements before further calculation.
Syntax
Math.abs(x)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | Number | A number whose absolute value you want to compute |
Return value
- The absolute value of
x, always a non-negative number. - Returns
NaNif the argument isNaNor cannot be converted to a number. - Returns
Infinityif the argument isInfinityor-Infinity. - Returns
0for±0.
Examples
Basic usage
Math.abs(5);
// 5
Math.abs(-5);
// 5
Math.abs(0);
// 0
Math.abs() also handles special numeric values consistently. Infinity stays Infinity regardless of sign, since the absolute value of an unbounded number is still unbounded. This is useful when you are computing ratios or normalizing signed data that may include extreme values.
With different numeric types
Math.abs(-3.14);
// 3.14
Math.abs(Infinity);
// Infinity
Math.abs(-Infinity);
// Infinity
When the input is not a number, Math.abs() returns NaN. This includes strings that cannot be parsed, undefined, and objects without a numeric valueOf(). Always validate inputs when the source is untrusted to avoid silent NaN propagation through downstream calculations.
With non-numeric values
Math.abs("hello");
// NaN
Math.abs(NaN);
// NaN
Passing a string that can be parsed as a number works: Math.abs("-5") returns 5. Strings that cannot be parsed return NaN.
The most practical application of Math.abs() is checking whether two floating-point values are close enough to be considered equal. Because IEEE 754 arithmetic introduces tiny rounding errors, direct === comparison often fails where you expect it to succeed. Math.abs(a - b) < tolerance is the standard workaround.
Practical example: tolerance check
function almostEqual(a, b, tolerance = 0.0001) {
return Math.abs(a - b) < tolerance;
}
console.log(almostEqual(0.1 + 0.2, 0.3));
// true
This is the standard pattern for comparing floating-point numbers, where exact equality (===) often fails due to rounding.
Math.abs() also appears naturally in distance formulas. The Euclidean distance between two points relies on squaring differences (which makes them positive), so Math.abs() is not strictly needed there, but in simpler 1D or axis-aligned distance checks the absolute difference is exactly what you want.
Practical example: distance calculation
function distance(x1, y1, x2, y2) {
return Math.sqrt(
Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)
);
}
console.log(distance(0, 0, 3, 4));
// 5
When you want the magnitude of a difference regardless of argument order, Math.abs() is the cleanest expression. It eliminates the need for a conditional that checks which value is larger before subtracting — you simply wrap the subtraction and get a non-negative result every time.
Practical example: temperature range
function temperatureRange(low, high) {
return Math.abs(high - low);
}
console.log(temperatureRange(20, 30));
// 10
console.log(temperatureRange(30, 20));
// 10
Wrapping the difference in Math.abs() means the argument order does not matter — you always get the magnitude of the difference.
You can combine Math.abs() with Math.min() and Math.sign() to clamp a signed value by magnitude rather than by range. This pattern preserves the sign while capping the absolute size, which is useful in physics simulations and signal processing.
Clamping a signed value
function signedClamp(value, maxMagnitude) {
const sign = value < 0 ? -1 : 1;
return sign * Math.min(Math.abs(value), maxMagnitude);
}
console.log(signedClamp(5, 3)); // 3
console.log(signedClamp(-5, 3)); // -3
console.log(signedClamp(2, 3)); // 2
Math.abs() internally coerces its argument to a number before computing the absolute value. Strings that represent valid numbers work, as do null and booleans. This is usually harmless when inputs are validated, but can mask bugs when unexpected types reach the call site.
Behavior with coercible strings
Math.abs() internally converts its argument to a number before computing the absolute value. This means strings that represent valid numbers work:
Math.abs("-42"); // 42
Math.abs("3.14"); // 3.14
Math.abs(""); // 0 (empty string coerces to 0)
Math.abs(null); // 0 (null coerces to 0)
Math.abs(true); // 1 (true coerces to 1)
Math.abs(false); // 0
Math.abs(undefined); // NaN
This implicit coercion is usually harmless when inputs are validated, but can mask bugs if unexpected types slip through. In TypeScript-heavy codebases, the type system prevents most of these cases.
Relation to Math.sign()
Math.abs() and Math.sign() are complementary. Any number equals Math.sign(x) * Math.abs(x). This lets you separate the magnitude and direction of a value for independent manipulation:
const x = -7;
const sign = Math.sign(x); // -1
const magnitude = Math.abs(x); // 7
const doubled = sign * (magnitude * 2); // -14
When Math.abs() helps
Math.abs() is the simplest way to measure how far a number is from zero. That is useful when the direction does not matter, such as comparing differences, checking tolerances, or normalizing signed values before further math. Instead of writing a conditional to handle positive and negative cases separately, you can collapse both paths into one magnitude calculation.
It also keeps intent obvious in code that works with noisy input. If a value might be above or below a target, Math.abs() turns the distance into a single positive number that is easy to compare or sort. That makes it a common building block in validation, physics-style calculations, and any feature that needs a stable size rather than a direction.
See Also
- Math.sign() — returns the sign of a number
- Math.sqrt() — returns the square root of a number
- Math.pow() — returns the base to the exponent power