JavaScript Math abs( ) Method

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

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • Output:
    2
    2.56

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



Below examples illustrate the Math abs( ) method in JavaScript:

  • 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

2
2.56

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

NaN

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

16

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.