JavaScript Math abs() method

The abs method in JavaScript is used to obtain the absolute value of a specified number. This method is considered a static function of the Math object.

Syntax

The syntax for the abs method is as follows:

Example

Math.abs(num)

Parameter

num - A number.

Return

An absolute value of a number.

JavaScript Math abs method example

In this section, we will explore the abs function by examining multiple examples.

Example 1

Consider the following illustration that demonstrates how to output the absolute value of a given number.

Example

<script>

document.writeln(Math.abs(-4)+"<br>");

document.writeln(Math.abs(-7.8)+"<br>");

document.writeln(Math.abs('-4'));

</script>

Output:

Output

4

7.8

4

Example 2

Let’s explore several scenarios in which the abs function yields a result of 0.

Example

<script>

document.writeln(Math.abs(null)+"<br>");

document.writeln(Math.abs([])+"<br>");

document.writeln(Math.abs(''));

</script>

Output:

Output

0

0

0

Example 3

Let’s explore scenarios in which the abs function yields NaN.

Example

<script>

document.writeln(Math.abs("string")+"<br>");

document.writeln(Math.abs([2,3])+"<br>");

document.writeln(Math.abs());

</script>

Output:

Output

NaN

NaN

NaN

Example 4

Let’s explore the abs function by creating some of your own test scenarios.

Example

<script>

function display()

{

  var x=document.getElementById("num").value;

  document.getElementById("result").innerHTML=Math.abs(x);

}

</script>

<form>

  Enter a number: <input type="text" id="num">

  <input type="button"  onclick="display()" value="submit">

  </form>

  <p><span id="result"></span></p>

Input Required

This code uses input(). Please provide values below: