Categories
Web development

JavaScript Math.abs()

JavaScript Math.abs()

The JavaScript abs() method returns the absolute value of a number.

Syntax:

Math.abs(number)

Example1:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to the absolute value of -5.45</p>
<button onclick="absExample()">Try it</button>
<p id="example-1"></p>

<script>
function absExample() {
  document.getElementById("example-1").innerHTML = Math.abs(-5.45);
}
</script>

</body>
</html>

Output:

Click the button to the absolute value of -5.45


A Number, expressing the absolute value of the defined number, or NaN if the value is not a number, or 0 if the value is null.

Example2:

<!DOCTYPE html>
<html>
<body>

<button onclick="absExample2()">Try it</button>
<p id="example-2"></p>

<script>
var example = Math.abs("Hello"); 

function absExample2() {
  document.getElementById("example-2").innerHTML = Math.abs(example);
}
</script>

</body>
</html>

Output:


Enjoy coding!

Read also:

JavaScript Math Object

JavaScript Introduction

JavaScript HTML DOM