References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Math.abs() method

Method JavaScript All modern browsers Updated
Quick answer

The Math.abs() method returns the absolute value of a number — its magnitude with any negative sign removed. Math.abs(-7) is 7, and Math.abs(7) is also 7. It's the standard way to get the distance between two values regardless of which is larger.

Overview

Math.abs() strips the sign off a number, giving you its distance from zero. -7 and 7 both become 7. It's a small method with one clear job, and it shows up whenever direction doesn't matter but magnitude does.

The everyday use is finding how far apart two numbers are without worrying which one is bigger: Math.abs(a - b) gives the difference as a positive number every time. That's the basis of distance checks, tolerance comparisons ("are these within 0.01 of each other?") and progress measurements.

It returns NaN for values that can't be converted to a number, and works fine on numeric strings via coercion. For a quick visual: Math.abs(-3.5) is 3.5 — it keeps the decimals, it only drops the sign.

Syntax

Math.abs(-7)    // 7
Math.abs(7)     // 7
Math.abs(a - b) // distance between a and b

Parameters

The Math.abs() method accepts the following parameters.

Parameter Description
x The number whose absolute (non-negative) value you want.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const target = 100, guess = 87;

  const off = Math.abs(target - guess);

  document.getElementById('out').textContent =
    'You were off by ' + off; // You were off by 13
</script>

Best practices

  • Use Math.abs(a - b) to get the difference between two numbers as a positive value.
  • Combine it with a small threshold for "close enough" floating-point comparisons.
  • It only removes the sign — decimals are preserved.
  • Non-numeric input returns NaN, so validate values you don't control.

Frequently asked questions

What does Math.abs() do?
It returns the absolute value of a number — the value without its sign, so it's always zero or positive.
How do I get the difference between two numbers?
Use Math.abs(a - b), which gives a positive result no matter which number is larger.
Does Math.abs() round the number?
No. It only removes the negative sign; the decimal part is kept. Use Math.round() to round.
How do I compare two floats for near-equality?
Check the absolute difference against a small tolerance: Math.abs(a - b) < 0.0001.