How to Use Math.abs in JavaScript: Absolute Value Explained
Use
Math.abs(value) in JavaScript to get the absolute (non-negative) value of a number. It returns the distance of the number from zero, ignoring its sign.Syntax
The Math.abs() function takes one argument and returns its absolute value.
value: The number you want to convert to a non-negative value.
javascript
Math.abs(value)Example
This example shows how Math.abs() converts negative and positive numbers to their absolute values.
javascript
console.log(Math.abs(-10)); console.log(Math.abs(5)); console.log(Math.abs(0)); console.log(Math.abs(-3.14));
Output
10
5
0
3.14
Common Pitfalls
Common mistakes include passing non-numeric values or forgetting that Math.abs() only works with numbers.
Passing undefined, null, or strings that can't convert to numbers will return NaN.
javascript
console.log(Math.abs('text')); // NaN console.log(Math.abs(undefined)); // NaN // Correct usage with numeric string: console.log(Math.abs('-20')); // 20
Output
NaN
NaN
20
Quick Reference
| Usage | Description |
|---|---|
| Math.abs(-5) | Returns 5, the absolute value of -5 |
| Math.abs(0) | Returns 0, absolute value of zero |
| Math.abs('10') | Returns 10, converts string to number |
| Math.abs('abc') | Returns NaN, invalid number string |
Key Takeaways
Math.abs(value) returns the absolute (non-negative) value of a number.
It works with positive, negative, zero, and numeric strings.
Passing non-numeric or undefined values returns NaN.
Use Math.abs to measure distance or magnitude without sign.
Always ensure the input can convert to a number for correct results.