JavaScript abs

The JavaScript abs function is a Math function that 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 abs function will return the absolute value of positive or negative number arguments.
  • If it is not a number, the abs function returns NaN.
  • If it is Null, the abs function returns Zero.

JavaScript abs Function Example

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

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptABSFunction</title>
</head>
<body>
  <h1> JavaScriptABSFunction</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 absolute Function directly on both the Positive integer and negative integer. Both of them will return the same output.

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

Next, We used the JavaScript abs Function on the Positive and negative Decimal values. If you observe the above screenshot, it works 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 the ABS Math function on the 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