Math.abs()
ES1+Returns the absolute value of a number.
Syntax
Math.abs(x)Parameters
x number A number
Return Value
The absolute value of the given number
Examples
console.log(Math.abs(-5));
console.log(Math.abs(5));
console.log(Math.abs(-3.14)); 📌 When to Use
Use Math.abs() when you need to calculate distances, differences between values regardless of direction, or when normalizing values that could be negative.
⚠️ Common Mistakes
Forgetting that Math.abs() returns NaN for non-numeric inputs like strings.
Using Math.abs() when you actually need to preserve the sign for calculations.
✅ Best Practices
Validate input is a number before using Math.abs() to avoid unexpected NaN results.
Use Math.abs() for calculating distances: distance = Math.abs(point1 - point2).
⚡ Performance Notes
Math.abs() is highly optimized in JavaScript engines and executes in constant O(1) time. It is faster than conditional checks like (x < 0 ? -x : x).
🌍 Real World Example
Temperature Difference Calculator
Calculate the absolute temperature difference between two cities for weather comparison.
function getTemperatureDifference(city1Temp, city2Temp) {
const difference = Math.abs(city1Temp - city2Temp);
return `Temperature difference: ${difference}°C`;
}
console.log(getTemperatureDifference(25, 18)); // "Temperature difference: 7°C"
console.log(getTemperatureDifference(-5, 10)); // "Temperature difference: 15°C"