Math.abs()

Returns the absolute value of a number, discarding its sign.

Signature
Math.abs(x)
  • Added in JavaScript ES1

Parameters

ParameterTypeDescription
$xnumberThe number for which to return the absolute value. Non-numbers are coerced first.

Return value

numberThe absolute value of x. Negative values and -0 return their opposite (a non-negative number); everything else is returned unchanged.

Math.abs() strips the sign off a number. It is the workhorse behind any "how far apart are these" question: subtract, then take the absolute value, and the order of the operands stops mattering.

When to reach for it

The most common real use is tolerance comparison for floating-point numbers. Because 0.1 + 0.2 !== 0.3, equality checks on computed floats are unreliable; Math.abs(a - b) < epsilon is the correct test. It also appears whenever you need a magnitude independent of direction: scroll deltas, temperature differences, error margins, distances on an axis.

What trips people up

The argument is coerced to a number, not type-checked. Math.abs("-1") is 1, Math.abs(null) and Math.abs([]) are both 0, and anything that cannot be coerced — {}, "abc", [1, 2], or no argument at all — yields NaN instead of throwing. If you are validating user input, check the type yourself; Math.abs() will quietly turn an empty string into zero.

Note also that Math.abs() normalises -0 to 0, which is the one case where it changes a value you might not expect it to touch. And since it takes exactly one argument, arr.map(Math.abs) is safe — the extra index and array arguments are ignored.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Comparing two floats within a tolerance instead of using ===
  • Measuring the distance between two positions on a number line
  • Normalising a scroll or drag delta before checking a threshold
  • Reporting an error margin without caring which side it fell on

Frequently asked questions

How do I get the absolute value of a number in JavaScript?

Call Math.abs(x) — it returns x without its sign. There is no unary absolute-value operator, though for a known-numeric value x < 0 ? -x : x is equivalent.

Why does Math.abs() return NaN?

Because the argument could not be coerced to a number — objects, multi-element arrays, non-numeric strings, undefined, and calling it with no argument all produce NaN. Math.abs() never throws for bad input, it returns NaN.

Is Math.abs() the right way to compare floating-point numbers?

Yes — write Math.abs(a - b) < epsilon rather than a === b, because arithmetic like 0.1 + 0.2 produces tiny representation errors. Number.EPSILON is a reasonable epsilon for values near 1, but scale it up for large magnitudes.

More examples

Coercion surprises

Every value goes through numeric coercion first. Single-element arrays and numeric strings convert cleanly, empty-ish values become 0, and only genuinely non-numeric values produce NaN. Nothing throws, so a bad input silently becomes a plausible-looking 0.

Example · javascript
console.log(Math.abs("-42")); // 42
console.log(Math.abs(null));  // 0
console.log(Math.abs(""));    // 0
console.log(Math.abs([]));    // 0
console.log(Math.abs([7]));   // 7
console.log(Math.abs([1, 2]));// NaN
console.log(Math.abs({}));    // NaN
console.log(Math.abs());      // NaN

Finding the closest value in a list

Absolute distance makes the comparison symmetric, so 6 (1.2 away) beats 9 (1.8 away) even though 9 is on the other side of the target. The final line shows every candidate's distance. Passing Math.abs straight to map also works, since it ignores the extra index argument.

Example · javascript
const target = 7.2;
const options = [1, 4, 9, 12, 6];

const closest = options.reduce((best, n) =>
  Math.abs(n - target) < Math.abs(best - target) ? n : best
);

console.log(closest); // 6
console.log(Math.abs(closest - target).toFixed(2)); // "1.20"
console.log(options.map((n) => Math.abs(n - target).toFixed(1)));

Discussion

  • Be the first to comment on this lesson.