JavaScript Absolute Value - Math.abs()

In this short tutorial, we look at the JavaScript absolute value (math.abs()) method. We explain the syntax with a real-world example.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Contents - Absolute Value Python:

TL;DR - How to find the absolute value in JavaScript?

The math.abs() function is used to return the absolute value in JavaScript. It negates the native sign of a number and returns the relevant positive value.

console.log(Math.abs(-2));

//Output = 2

JavaScript Absolute Value:

JavaScript Absolute value is a method of the Math object in JavaScript. This method helps return the absolute values of a number. Absolute value or modules essentially means a non-negative value of x.

To understand the math involved let’s first understand what absolute value actually means. Absolute value is the distance between any number and 0 on the number line. Since it is the distance, there are no negative values.

Subsequently, when a 0 is passed, JavaScript returns 0 as the distance would also be 0.

How to use the Math.abs() function?

Using the Math.abs() method is quite straightforward. The only thing that you have to keep in mind is that abs() is a static method of Math. Hence you would have to add the Math. prefix in case you want to use it.

JavaScript Absolute Value - Syntax:

Math.abs(x)

Parameters:

X - A number

Return Values:

  • “x” if x > 0
  • “x” if x < 0
  • “-x” if x = 0

Code and Explanation:

The best way to familiarise yourself with the JavaScript Absolute method is to practice and try breaking it. In the below code we have used math.abs() methods on a list of values.

Math.abs(-10);     // 10
Math.abs(10);       // 10
Math.abs('-10');     // 10
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs(null);     // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('Ten'); // NaN
Math.abs();         // NaN

Another important point to remember while using the math.abs() methods, is it converts strings containing a number and returns its absolute value.

Closing Thoughts - JavaScript Absolute method:

This method is mostly used before displaying a particular value. A common example would be while displaying distance on a map. In cases where you cross your destination, you are not returned with a negative value but rather the absolute value from the destination.