Math.abs for Absolute Values
What you'll learn: How to strip away the negative sign from any number and work with its pure magnitude.
What Is an Absolute Value?
The absolute value of a number is its distance from zero, ignoring whether it's positive or negative. Think of it like asking "how far?" rather than "in which direction?" — a thermometer might show -5°C, but the magnitude of the temperature change from 0°C is still 5 degrees.
In JavaScript, Math.abs() converts any number to its non-negative equivalent.
Using Math.abs()
The method takes one argument and returns its absolute value:
Math.abs(-42); // 42
Math.abs(42); // 42
Math.abs(-3.14); // 3.14
Math.abs(0); // 0
Notice that positive numbers stay positive, and zero stays zero. Only negative numbers change.
Common Use Cases
Calculating distance or difference:
let a = 100;
let b = 75;
let difference = Math.abs(a - b); // 25 (not -25)
Working with temperature changes, elevation differences, or any measurement where direction doesn't matter:
let temperature = -15;
let magnitude = Math.abs(temperature); // 15
Special Values
Math.abs(-Infinity); // Infinity
Math.abs(NaN); // NaN
Even -Infinity becomes positive Infinity, but NaN remains NaN (as with most math operations).
Key Takeaway: Math.abs() returns the magnitude of a number without its sign, converting negatives to positives while leaving positives unchanged — essential whenever you care about "how much" but not "which direction."