JavaScript Math.abs() | Find absolute value of a number

The JavaScript Math.abs() method is used when we need to get the actual magnitude of a numerical value, irrespective of its sign. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="para1"></p>
   <p id="para2"></p>
   <p id="para3"></p>
   <p id="para4"></p>
 
   <script>
      let a = 0;
      let b = 5;
      let c = -10;
      let d = +45;

      document.getElementById("para1").innerHTML = Math.abs(a);
      document.getElementById("para2").innerHTML = Math.abs(b);
      document.getElementById("para3").innerHTML = Math.abs(c);
      document.getElementById("para4").innerHTML = Math.abs(d);
   </script>
   
</body>
</html>
Output

JavaScript Math.abs() Syntax

The syntax of Math.abs() method in JavaScript is:

Math.abs(x)

The x parameter is required, refers to a number.

The Math.abs() returns the absolute value of a number defined as its parameter. This method returns:

  • NaN if x is not a number
  • Otherwise 0 if x is null

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋