What is the use of Math.abs() method in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Math.abs()

Math.abs() gives absolute value of a number, that is

                                                       p  if p > 0
                               Math.abs(p) =  |p| = {  0  if p = 0                                                                                         -p  if p < 0

If  the above mathematical notation is observed , when p is positive the absolute value took positive p and when the value is negative absolute value take -(p).For suppose let the value of p be -5 then according to the above notation  the absolute value takes -p that is -(-5) which is equal to +5.So, from this we can get that absolute value gives only positive value irrespective of sign of the number whether positive or negative.

In the following example the absolute value of the difference between 1 and 9 is positive despite the actual value is negative(-8).

Example-1                         

Live Demo

<html>
<body>
<script>
   function myDiff(a, b) {
      return Math.abs(a - b);
   }
   document.write(myDiff(1, 9));
</script>
</body>
</html>

Output

8

Example-2

The following example returns a positive value rather than given negative value using Math.abs() method.

 Live Demo

<html>
<body>
<p id="absolute"></p>
<script>
   document.getElementById("absolute").innerHTML = Math.abs(-5.13);
</script>
</body>
</html>

Output

5.13
raja
Published on 28-May-2019 15:49:40
Advertisements