JavaScript Math abs() Method
Javascript Math.abs() method is used to return the absolute value of a number. It takes a number as its parameter and returns its absolute value.
Syntax:
Math.abs(value)Parameters:
This method accepts a single parameter as mentioned above and described below:
- value: The number whose absolute value is to be found is passed as the parameter to this function.
Return Value:
The absolute value of the number passed as a parameter. The below examples illustrate the Math abs( ) method in JavaScript:
Example 1: This example shows the use of the Math.abs() method in javascript.
console.log(Math.abs(2));
console.log(Math.abs(2.56));
Output
2 2.56
Example 2: This example shows the return value of Math.abs() method when the parameter is a string value.
console.log(Math.abs("Geeksforgeeks"));
Output
NaN
Example 3: This example shows the return value of Math.abs() method when the parameter is an arithmetic expression.
console.log(Math.abs(7+9));
Output
16
Errors and Exceptions:
- A non-numeric string passed as a parameter returns NaN.
- An array with more than 1 integer passed as a parameter returns NaN.
- An empty variable passed as a parameter returns NaN.
- An empty string passed as a parameter returns 0.
- An empty array passed as a parameter returns 0.
We have a complete list of Javascript Math Objects methods, to check those please go through this Javascript Math Object Complete reference article.
Supported Browsers
- Chrome 51
- Edge 15
- Firefox 54
- Safari 10
- Opera 38
JavaScript Math abs() Method – FAQs
What does the Math.abs() method do in JavaScript?
The Math.abs() method returns the absolute value of a number, which is the non-negative value of the number without regard to its sign.
How does Math.abs() handle non-numeric arguments?
If the argument is not a number, Math.abs() first attempts to convert it to a number before returning the absolute value. If the argument cannot be converted to a number, the result is NaN (Not-a-Number).
What happens if the argument is a negative number?
If the argument is a negative number, Math.abs() returns the positive equivalent of that number.
Can Math.abs() handle special numeric values like NaN, Infinity, and -Infinity?
Yes,
Math.abs()can handle special numeric values:
Math.abs(NaN)returnsNaN.Math.abs(Infinity)returnsInfinity.Math.abs(-Infinity)returnsInfinity.
What is the most common use of the Math.abs() method?
Most Common Use Cases:
- Calculating distances or differences where only the magnitude matters.
- Normalizing data by converting all values to their positive equivalents.
- Implementing mathematical functions and algorithms that require non-negative inputs.


