basic
Math.abs
Returns the absolute value of a number — its distance from zero without regard to sign. Useful for differences, magnitudes, and tolerance checks.
Math.abs(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | The input number; strings and booleans are coerced |
| NaN | Math.abs(NaN) returns NaN; Math.abs(undefined) also returns NaN |
| -0 | Math.abs(-0) returns 0, collapsing the sign |
Examples
console.log(Math.abs(-5)); // 5 Classic absolute value.
console.log(Math.abs(5)); // 5 Positives are returned unchanged.
console.log(Math.abs(-3.14)); // 3.14 Works for floats.
console.log(Math.abs(a - b) < 1e-9); // true/false Standard floating-point equality within an epsilon tolerance.
Gotcha
For extremely large negatives, Math.abs(Number.MIN_SAFE_INTEGER) is safe, but Math.abs(-Infinity) returns Infinity — verify with Number.isFinite before dividing.
Related
Math.sign
Returns the sign of a number as 1, -1, 0, -0, or NaN. Introduced in ES2015 as a compact replacement for the ternary `x > 0 ? 1 : x < 0 ? -1 : 0`.
Math.sqrt
Returns the positive square root of a number. Equivalent to Math.pow(x, 0.5) but faster and clearer.
Math.hypot
Returns the square root of the sum of squares of its arguments — the Euclidean norm. Introduced in ES2015 and safer than manual sqrt(a*a + b*b) against overflow.
Math.pow
Returns base raised to the power of exponent. In modern code the `**` operator (ES2016) is usually preferred for readability and identical semantics.
Math.cbrt
Returns the cube root of a number. Introduced in ES2015, and unlike sqrt it handles negative inputs correctly.