# What is Math.abs() method and How to use it in JavaScript?

Explore the powerful math.abs() method, also known as the Absolute Value function, in JavaScript.

This article will walk you through its definition, usage, and examples of this fundamental mathematical concept.

So to have a better understanding concerning math.abs in JavaScript, keep on reading!

## What is Math.abs in JavaScript

Math.abs() is a static method in JavaScript that returns the absolute value of a number. It simply means that if the input is negative, it will return the positive equivalent of that number.

If the input is already positive, it will return the same value. For instance, Math.abs(-8) would return 8, while Math.abs(8) would also return 81.

This method can be used on any number, including negative zero and negative infinity.

Here’s another example, Math.abs(-0) would return 0, and Math.abs(-Infinity) would return Infinity.

Important to note that Math.abs() is a static method of the Math object, so you always use it as Math.abs() rather than as a method of a Math object you created.

Math.abs(number)

A number

### Return Value

It returns the absolute value of the given number.

For non-numeric string arguments, it yields NaN (Not a Number).

## How to use math.abs() JavaScript?

Here are some examples of how to use Math.abs() in JavaScript:

### Example 1:

let a = Math.abs(-8.25);
console.log(a)

Output:

8.25

### Example 2:

let b = Math.abs(8.25);
console.log(b)

Output:

8.25

### Example 3:

let c = Math.abs("Sample");
console.log(c)

Output:

NaN

### Example 4:

let d = Math.abs(null);
console.log(d)

Output:

0

### Example 5:

let e = Math.abs(9-1);
console.log(e)

Output:

8

As you have noticed, Math.abs() can be used on any number, including negative zero and negative infinity.

Apart from that, it can also be used on non-numeric values, but the result may not be what you expect.

Here are some more examples of how to use Math.abs() in different scenarios:

### Example 6:

Find the distance between two points on a number line

let a = 10;
let b = 2;
let distance = Math.abs(a - b);
console.log(distance)

Output:

8

### Example 7:

Find the absolute difference between two numbers

let num1 = 50;
let num2 = 2;
let difference = Math.abs(num1 - num2);
console.log(difference)

Output:

48

### Example 8:

Find the absolute value of an array of numbers

let numbers = [-8, -1, 10, 9, 4];
let absoluteValues = numbers.map(Math.abs);
console.log(absoluteValues)

Output:

[ 8, 1, 10, 9, 4 ]

## Conclusion

In conclusion, this article discuss the Math.abs() method in JavaScript, which is a powerful tool for obtaining the absolute value of a number, whether positive or negative.

It allows us to find the positive equivalent of a negative number or simply maintain the value of a positive number.

Additionally, it can be used on non-numeric values, but it will result in NaN (Not a Number).