Math.abs() in JavaScript with Examples

Learn how Math.abs() works in JavaScript with absolute value examples, type coercion behavior, and difference calculations.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Math.abs() in JavaScript with Examples

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.

javascript
console.log("abs-number-1:", Math.abs(-23));
console.log("abs-number-2:", Math.abs(45));
Output

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.

javascript
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([]));
Output

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.

javascript
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));
Output

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.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …