Math.abs() returns the absolute value of a number in JavaScript. It is useful when you want to remove the sign from a number, compare distances, or calculate a magnitude.
The method belongs to the Math object, so it works with numeric values and values that can be converted to numbers. If you are working with rounding too, Math.floor in JavaScript and Math.ceil in JavaScript are the nearby topics.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Method 1: Get the absolute value of a number
The method strips the negative sign and returns the positive magnitude.
console.log("abs-number-1:", Math.abs(-23));
console.log("abs-number-2:", Math.abs(45));You should see 2 lines, in order: abs-number-1: 23, abs-number-2: 45.
This is the most direct use of the method.
Method 2: Let Math.abs() coerce values
If the value can be converted to a number, the method can still return an absolute result.
console.log("abs-string:", Math.abs("-23"));
console.log("abs-true:", Math.abs(true));
console.log("abs-false:", Math.abs(false));
console.log("abs-array:", Math.abs([]));You should see 4 lines, in order: abs-string: 23, abs-true: 1, abs-false: 0, abs-array: 0.
This is useful to know because coercion can make the result look simpler than the input type suggests.
Method 3: Use Math.abs() for differences
The method is often used when you need the gap between two values without caring which one is larger.
function diff(a, b) {
return Math.abs(a - b);
}
console.log("abs-diff-1:", diff(3, 2));
console.log("abs-diff-2:", diff(2, 3));You should see 2 lines, in order: abs-diff-1: 1, abs-diff-2: 1.
This pattern is common in distance checks, timing differences, and comparison logic.
Summary
Math.abs() is the JavaScript absolute value method. Use it when you want to remove a sign, compare differences, or work with a magnitude instead of a signed number.
