The abs()
method finds the absolute value of the specified number (without any sign) and returns it.
Example
// find absolute value of -2
number= Math.abs(-2);
console.log(number);
// Output: 2
abs() Syntax
The syntax of the Math.abs()
method is:
Math.abs(number)
Here, abs()
is a static method. Hence, we are accessing the method using the class name, Math
.
abs() Parameter
The Math.abs()
method takes a single parameter:
number
- whose absolute value is to be returned
abs() Return value
The abs()
method returns:
- the absolute value of the specified number
- NaN for non-numeric string arguments
Example 1: JavaScript Math.abs() with Numeric Arguments
value1 = Math.abs(57);
console.log(value1); // 57
value = Math.abs(-3);
console.log(value); // 3
Example 2: Math.abs() with Numeric Strings
value1 = Math.abs("57");
console.log(value1); // 57
value = Math.abs("-230");
console.log(value); // 230
Here, the abs()
method treats numeric strings "57"
and "-230"
as numbers and returns their absolute value as the output.
Example 3: Math.abs() with Non-Numeric Strings
// abs() with non-numeric argument
value = Math.abs("Programiz");
console.log(value);
// Output: NaN
Here, we have used the abs()
method with the non-numeric string "Programiz"
. In this case, we get NaN as output.
Recommended readings: