JavaScript | Math.abs( ) function
The Math.abs() function in JavaScript 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: The number whose absolute value is to be found is passed as the parameter to this function.
Returns : Absolute value of the number passed as parameter.
Example:
Input : Math.abs(-4) Output : 4 Input : Math.abs(0) Output : 0
Errors and Exceptions:
1. A non-numeric string passed as parameter returns NaN
2. An array with more than 1 integer passed as parameter returns NaN
3. An empty variable passed as parameter returns NaN
4. An empty string passed as parameter returns 0
5. An empty array passed as parameter returns 0
Below are some examples that illustrate the Math.abs() function in JavaScript:
Example 1:
<!-- NEGATIVE NUMBER EXAMPLE --><script type="text/javascript"> document.write(Math.abs(-2)); document.write(Math.abs(-2.56)); </script> |
Output:
2 2.56
Example 2:
<!-- POSITIVE NUMBER EXAMPLE --><script type="text/javascript"> document.write(Math.abs(2)); document.write(Math.abs(2.56)); </script> |
Output:
2 2.56
Example 3:
<!-- STRING EXAMPLE --><script type="text/javascript"> document.write(Math.abs("Geeksforgeeks")); </script> |
Output:
NaN
Example 4:
<!-- ADDITION INSIDE FUNCTION EXAMPLE --><script type="text/javascript"> document.write(Math.abs(7+9)); </script> |
Output:
16
Supported Browsers: The browsers supported by JavaScript Math.abs( ) function are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- JavaScript | toPrecision( ) Function
- JavaScript | Array every() function
- JavaScript | Symbol.for() function
- JavaScript | String() Function
- JavaScript | toFixed( ) Function
- JavaScript | Function Definitions
- JavaScript | toString( ) function
- JavaScript | Function Invocation
- JavaScript | Array some() function
- JavaScript | Math.E() function
- JavaScript | Array.of() function
- JavaScript | Function Parameters
- JavaScript | Function Apply
- JavaScript | toExponential() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



