JavaScript Math abs() method - JavaScript Tutorial

JavaScript Math abs() method

BLUF: This tutorial on JavaScript Math abs() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Math abs() method

Understanding JavaScript Math abs() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience