JavaScript ABS

The JavaScript Abs function is a Math function, which returns the absolute (positive) value of the specified expression or a specific number. The syntax of the JavaScript Abs Function is:

Math.abs(number);
  • The JavaScript abs function will return the absolute value of positive or negative number arguments.
  • If it is not a number, abs function returns NaN.
  • If it is Null, abs function returns Zero.

JavaScript Abs Function Example

In this JavaScript absolute Function example, We are going to find the absolute values of different data types and display the output

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript ABS Function </title>
</head>
<body>
  <h1> JavaScript ABS Function </h1>
  <p id = "Pos"></p>
  <p id = "Neg"></p>
  <p id = "Dec"></p>
  <p id = "Neg_Dec"></p>
  <p id = "Str"></p>
  <p id = "Exp"></p>
  <p id = "Null"></p>
  <p id = "Multi"></p>
  <script>
    document.getElementById("Pos").innerHTML = Math.abs(20);
    document.getElementById("Neg").innerHTML = Math.abs(-20);
    document.getElementById("Dec").innerHTML = Math.abs(10.45);
    document.getElementById("Neg_Dec").innerHTML = Math.abs(-6.45);
    document.getElementById("Str").innerHTML = Math.abs("JavaScript");
    document.getElementById("Null").innerHTML = Math.abs(null);
    document.getElementById("Multi").innerHTML = Math.abs(2 + 55 - 77);
  </script>
</body>
</html>
JavaScript ABS Function

First, We used the JavaScript absolute Function directly on both the Positive integer and negative integer. Both of them will return same output

 document.getElementById("Pos").innerHTML = Math.abs(20);
 document.getElementById("Neg").innerHTML = Math.abs(-20);

Next, We used the ABS Function on the Positive and negative Decimal values. If you observe the above screenshot, Abs function working correctly with decimal values

 document.getElementById("Dec").innerHTML = Math.abs(10.45);
 document.getElementById("Neg_Dec").innerHTML = Math.abs(-6.45);

Next, We tried JavaScript absolute Function on the string value. It will return NaN

document.getElementById("Str").innerHTML = Math.abs("JavaScript");

Next, We tried ABS Math function on Null value, and it returns Zero as output

document.getElementById("Null").innerHTML = Math.abs(null);

In the below statement, we used the ABS Function directly on multiple values.

 document.getElementById("Multi").innerHTML = Math.abs(2 + 55 - 77);

It means, ABS(2 + 55 – 77) => ABS (-20) = 20