JavaScript Math.abs()

Math.abs(x) returns the absolute value of a number: negative values become positive, while positive values and zero remain unchanged.

console.log(Math.abs(-5));   // 5
console.log(Math.abs(5.56)); // 5.56

Math.abs() syntax Top ↑

Math.abs(x)

The argument is converted to a number. If conversion fails, the result is NaN.

Positive, negative and zero Top ↑

console.log(Math.abs(-2.5));   // 2.5
console.log(Math.abs(1.355));  // 1.355
console.log(Math.abs(0));      // 0

Absolute difference between two values Top ↑

Absolute value is useful when you care about distance or magnitude rather than direction.

const first = 43;
const second = 64;
console.log(Math.abs(first - second)); // 21

Numeric strings and invalid values Top ↑

console.log(Math.abs("-12.78")); // 12.78
console.log(Math.abs(""));       // 0
console.log(Math.abs("hello"));  // NaN

For user input, explicitly convert and validate the value rather than relying on coercion.

Practical uses Top ↑

function distance(a, b) {
  return Math.abs(a - b);
}
console.log(distance(18, 27)); // 9

Interactive Math.abs() demo Top ↑

Use the Math.abs() demo to enter your own value and see the absolute result.

Math.log()




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer