JavaScript Math.abs()
Syntax & Examples


Math.abs() static-method

The Math.abs() method in JavaScript returns the absolute value of a number. This method is a static method of the Math object, and it always returns a positive number or 0.


Syntax of Math.abs()

The syntax of Math.abs() static-method is:

Math.abs(x)

This abs() static-method of Math returns the absolute value of x.

Parameters

ParameterOptional/RequiredDescription
xrequiredA number whose absolute value is to be returned. If the value of x is negative, it will be converted to positive.

Return Type

Math.abs() returns value of type Number.



✐ Examples

1 Using Math.abs() with a positive number

In JavaScript, we can use the Math.abs() method to get the absolute value of a positive number.

For example,

  1. We call the Math.abs() method with a positive number x.
  2. The absolute value is returned and stored in the variable result.
  3. We log result to the console using console.log() method.

JavaScript Program

const x = 42;
const result = Math.abs(x);
console.log(result);

Output

42

2 Using Math.abs() with a negative number

In JavaScript, we can use the Math.abs() method to get the absolute value of a negative number.

For example,

  1. We call the Math.abs() method with a negative number x.
  2. The absolute value is returned and stored in the variable result.
  3. We log result to the console using console.log() method.

JavaScript Program

const x = -42;
const result = Math.abs(x);
console.log(result);

Output

42

3 Using Math.abs() with zero

In JavaScript, we can use the Math.abs() method to get the absolute value of zero.

For example,

  1. We call the Math.abs() method with zero x.
  2. The absolute value is returned and stored in the variable result.
  3. We log result to the console using console.log() method.

JavaScript Program

const x = 0;
const result = Math.abs(x);
console.log(result);

Output

0

Summary

In this JavaScript tutorial, we learned about abs() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.