JavaScript Math.abs() Method
The JavaScript Math.abs() method accepts a number as a parameter and returns the absolute value of the provided number. If the provided value is not a valid number or cannot be converted to a number, the result is NaN. If the provided value is null, the method returns 0.
In mathematics, an absolute value of a number represents its distance from 0 on the number line. In short, it's the positive value of a number, regardless of its positive or negative sign. For instance, the absolute value of both -5 and 5 is 5.
Syntax
Following is the syntax of JavaScript Math.abs() method −
Math.abs(x);
Parameters
This method accepts only one parameter. The same is described below −
- x: A number.
Return value
This method retuns a number which represents the absolute value of the provided number.
Example 1
In the following example, we are demonstrating the basic usage of JavaScript Math.abs() method −
<html> <body> <script> let a = Math.abs(15); let b = Math.abs(-15) let c = Math.abs(5-4.5); let d = Math.abs(3-6); document.write(a + "<br>" + b + "<br>" + c + "<br>" + d) </script> </body> </html>
Output
As we can see the output, this method returned the absolute values for all the provided numbers.
Example 2
If we provide "null" as a value to this method, it returns 0 as result −
<html> <body> <script> let a = Math.abs(null); document.write(a); </script> </body> </html>
Output
As we can see the output, 0 is returned.
Example 3
If we provide an invalid value to this method, it returns "NaN" as result −
<html>
<body>
<script>
let a = Math.abs("Tutorialspoint");
document.write(a);
</script>
</body>
</html>
Output
As we can see the output, NaN is returned.