JavaScript Math.abs() Method



The JavaScript Math.abs() method accepts a number as a parameter and returns the absolute value of the provided number. If the provided value is not a valid number or cannot be converted to a number, the result is NaN. If the provided value is null, the method returns 0.

In mathematics, an absolute value of a number represents its distance from 0 on the number line. In short, it's the positive value of a number, regardless of its positive or negative sign. For instance, the absolute value of both -5 and 5 is 5.

Syntax

Following is the syntax of JavaScript Math.abs() method −

Math.abs(x);

Parameters

This method accepts only one parameter. The same is described below −

  • x: A number.

Return value

This method retuns a number which represents the absolute value of the provided number.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Math.abs() method −






Output

As we can see the output, this method returned the absolute values for all the provided numbers.

Example 2

If we provide "null" as a value to this method, it returns 0 as result −






Output

As we can see the output, 0 is returned.

Example 3

If we provide an invalid value to this method, it returns "NaN" as result −






Output

As we can see the output, NaN is returned.

Advertisements