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.56Math.abs(x)The argument is converted to a number. If conversion fails, the result is NaN.
console.log(Math.abs(-2.5)); // 2.5
console.log(Math.abs(1.355)); // 1.355
console.log(Math.abs(0)); // 0Absolute 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)); // 21console.log(Math.abs("-12.78")); // 12.78
console.log(Math.abs("")); // 0
console.log(Math.abs("hello")); // NaNFor user input, explicitly convert and validate the value rather than relying on coercion.
function distance(a, b) {
return Math.abs(a - b);
}
console.log(distance(18, 27)); // 9Use the Math.abs() demo to enter your own value and see the absolute result.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.