Math.abs()

Returns the absolute value of a number, that is, its distance from zero.

Returns
The absolute value of x.
On this page

Example

#
JavaScript
console.log(Math.abs(-7))
console.log(Math.abs(7))

const target = 100
const results = [96, 108, 99]
console.log(results.map((r) => Math.abs(r - target)))
Console
7
7
[4, 8, 1]

Definition and usage

#

The Math.abs() function returns the number without its minus sign. For positive numbers and zero the result is unchanged, and negative numbers become positive.

It’s useful when only the size of a difference matters, not its direction: the distance between points, the difference in scores, the deviation from a target.

It also works on strings that can be converted to a number, but it’s better to pass it numbers directly, so you don’t rely on automatic conversion.

Syntax

#
Syntax
Math.abs(x)

Parameters

#
  • x

    number

    The number whose absolute value you want to calculate.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Compare floating-point numbers with a tolerance: Math.abs(a - b) < 1e-9 instead of a === b.
  • The difference "how far off was I" is always Math.abs(result - target).

Related entries

#

Spotted a mistake or missing an example? Write to us.