Absolute differences
Compute distance or difference without caring which operand is larger.
JavaScript · Function
Math.abs() returns the absolute value of a number. It converts its argument to a Number and returns a non-negative result, or NaN when conversion is not possible.
Math.abs() converts its argument to a Number and returns its magnitude without a negative sign. Negative values, including negative zero, are sign-reversed; other numeric values are returned unchanged, while values that cannot be converted produce NaN.
Math.abs(x)| Name | Type | Description |
|---|---|---|
x | number | The value whose absolute magnitude should be returned; it is converted to a number. |
The absolute value of x; the result is a positive number or 0, or NaN when conversion fails.
const difference = (a, b) => Math.abs(a - b);
console.log(difference(3, 5)); // 2
console.log(difference(5, 3)); // 2Computes the non-negative distance between two numbers regardless of their order.
Compute distance or difference without caring which operand is larger.
Normalize a signed measurement into a magnitude.
Check whether a numeric result is within a tolerance.
Math.abs(x) returns the absolute value of x, so the result is non-negative. A negative input is changed to its opposite, while a non-negative input is returned unchanged.
Follow-up: What happens for -0? It returns positive zero, because negative zero is explicitly converted to its opposite.
The function first converts its argument to a number. For example, a numeric string can become a number, while an input that cannot be converted produces NaN.
Follow-up: What does Math.abs([2]) return? The array is converted to the string "2", then to the number 2, so the result is 2.
Math.abs() is a static method of the Math namespace, and Math is not a constructor. Therefore, call it as Math.abs(value), rather than through a Math instance.
Follow-up: Can Math.abs() process BigInt values? No; Math functions operate on Number values, not BigInt values.
Math.hypot()MathNumber