Skip to content
Related Articles

Related Articles

JavaScript Math abs( ) Method

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 Oct, 2022
Improve Article
Save Article

The 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.

Returns: Absolute value of the number passed as a parameter. The below examples illustrate the Math abs( ) method in JavaScript:

Below is an example of the Math abs() method.

Example: 

JavaScript




<script type="text/javascript">
    console.log(Math.abs(-2)+"<br>");
    console.log(Math.abs(-2.56));       
</script>


Output:

2
2.56

Example 1:

Input  : Math.abs(-4)
Output : 4

Example 2:

Input : Math.abs(0)
Output : 0

Errors and Exceptions:

  • A non-numeric string passed as parameter returns NaN.
  • An array with more than 1 integer passed as parameter returns NaN.
  • An empty variable passed as parameter returns NaN.
  • An empty string passed as parameter returns 0.
  • An empty array passed as parameter returns 0.

More example codes for the above method are as follows: 

Program 1: 

JavaScript




<!-- POSITIVE NUMBER EXAMPLE -->
<script type="text/javascript">
    console.log(Math.abs(2)+"<br>");
    console.log(Math.abs(2.56));       
</script>


Output:

2
2.56

Program 2: 

JavaScript




<!-- STRING EXAMPLE -->
<script type="text/javascript">
    console.log(Math.abs("Geeksforgeeks"));       
</script>


Output:

NaN

Program 3: 

JavaScript




<!-- ADDITION INSIDE FUNCTION EXAMPLE -->
<script type="text/javascript">
    console.log(Math.abs(7+9));       
</script>


Output:

16

Supported Browsers:

  • Google Chrome 1 and above
  • Internet Explorer 3 and above
  • Firefox 1 and above
  • Opera 3 and above
  • Safari 1 and above

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!