Math.abs()

ES1+

Returns the absolute value of a number: the value itself if it is positive or zero, and its negation if it is negative. The argument is coerced to a number first, so numeric strings work while non-numeric input yields NaN, and Math.abs(-0) returns 0.

Syntax

Math.abs(x)

Parameters

x number

A number

Return Value

number

The absolute value of the given number

Examples

JavaScript
console.log(Math.abs(-5));
console.log(Math.abs(5));
console.log(Math.abs(-3.14));
Output:
// 5 5 3.14

📌 When to Use

Use Math.abs() whenever only magnitude matters and direction does not: measuring the distance between two values on a number line (prices, temperatures, coordinates, scroll positions), checking whether two floating-point results are "close enough" by bounding their difference, computing error margins and deviations in statistics, or normalizing deltas before formatting ("3 days ago" and "in 3 days" share the same magnitude). It is the standard first step in tolerance comparisons: because binary floating point cannot represent values like 0.1 exactly, equality checks on computed floats should be written as Math.abs(a - b) < epsilon rather than a === b, with an epsilon scaled to the numbers involved (Number.EPSILON works for values near 1). In geometry and game code it appears in Manhattan distances, bounding-box overlap tests, and swipe-gesture thresholds where you care how far a pointer moved, not which way. Skip it when sign is information you still need, for example profit versus loss in accounting, and when you are about to square the value anyway, since squaring already discards sign. For BigInt values Math.abs() throws; write the conditional yourself or convert deliberately.

⚠️ Common Mistakes

Trusting coercion blind spots: Math.abs("") , Math.abs(null), and Math.abs([]) all return 0, and Math.abs(true) returns 1, because the argument is coerced with the same rules as Number(). A missing field that arrives as null thus looks like a legitimate zero distance instead of an error; validate types before the math.

Expecting NaN inputs to fail loudly. Math.abs(undefined) and Math.abs("abc") return NaN, which then poisons downstream arithmetic silently, every comparison with NaN is false, so records neither match filters nor trip alarms. Guard with Number.isFinite() at data boundaries.

Discarding sign that the logic still needs: computing Math.abs(balance) before display and then reporting a negative account as positive, or taking the absolute difference of timestamps when "which came first" was the actual question. Keep the signed value and take Math.abs() only at the final magnitude step.

Using a fixed Number.EPSILON tolerance for numbers far from 1: Number.EPSILON is the gap between 1 and the next float, so Math.abs(a - b) < Number.EPSILON is far too strict for values in the millions (where representable floats are much farther apart) and too lax near 1e-20. Scale the tolerance: epsilon * Math.max(1, Math.abs(a), Math.abs(b)).

Assuming Math.abs() always returns a "safe" positive number: Math.abs(-Infinity) is Infinity, and although JavaScript numbers are doubles (so unlike C, Math.abs(Number.MIN_SAFE_INTEGER) is fine), Infinity and NaN still flow through and need explicit handling in validation code.

✅ Best Practices

Write float comparisons as a named helper, approxEqual(a, b, eps), built on Math.abs(a - b) with a relative epsilon, so the subtle tolerance logic exists once and 0.1 + 0.2 !== 0.3 surprises stay out of business code.

Validate before coercing: accept only values passing Number.isFinite(x) into distance and difference math, turning nulls and strings into explicit errors instead of silent zeros and NaNs.

Prefer purpose-built alternatives when they express intent better: Math.hypot(dx, dy) for Euclidean distance instead of manual abs-square-sum, and Math.sign() when you need direction rather than magnitude, they read as the formula they implement.

In UI code, pair Math.abs() with the sign taken separately: const magnitude = Math.abs(delta), direction = Math.sign(delta), then format each independently ("▲ 3.2%" versus "▼ 3.2%"); this keeps display logic declarative.

For money, avoid floating differences entirely where possible: represent amounts in integer minor units (cents, won) so Math.abs(a - b) is exact integer arithmetic; floats enter only at formatting time.

⚡ Performance Notes

Math.abs() compiles to a single hardware instruction in optimized code (clearing the IEEE 754 sign bit), and modern engines inline it, so it is as fast as arithmetic gets, faster in practice than a hand-written ternary (x < 0 ? -x : x) because the branchless form avoids branch misprediction on mixed-sign data. There is no allocation and no observable cost even in per-pixel or per-frame loops processing millions of values. Consequently, performance never justifies avoiding it; clarity does the deciding. The one performance-adjacent caveat is monomorphism: feeding it a mix of small integers and heap-allocated doubles from the same call site can deoptimize surrounding code slightly, a general JavaScript numeric concern rather than anything specific to this function. Type-stable inputs (all doubles, as in typed arrays) keep hot numeric loops on the fast path.

🌍 Real World Example

Temperature Difference Calculator

Comparing readings from two sources, cities, sensors, price feeds, is a magnitude question: how far apart are they, regardless of which is higher. This example computes an absolute temperature difference so the comparison text ("differs by 7°") reads naturally in both directions, while deriving the direction separately for the "warmer/colder" phrasing. That separation of magnitude from sign is the reusable lesson: the same structure powers price-change badges, sensor-drift alarms, and accessibility checks that measure contrast differences.

function getTemperatureDifference(city1Temp, city2Temp) {
  const difference = Math.abs(city1Temp - city2Temp);
  return `Temperature difference: ${difference}°C`;
}

console.log(getTemperatureDifference(25, 18)); // "Temperature difference: 7°C"
console.log(getTemperatureDifference(-5, 10)); // "Temperature difference: 15°C"

Related Methods