JavaScript Math abs()

The JavaScript Math.abs() function returns the absolute value of a number.

Absolute value of a number x, denoted by |x|, is defined as:

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

The syntax of the Math.abs() function is:

Math.abs(x)

abs(), being a static method, is called using the Math class name.


Math.abs() Parameters

The Math.abs() function takes in:

  • x - A Number whose absolute value is to be returned.

Return value from Math.abs()

  • Returns the absolute value of the specified number.
  • Returns NaN if:
    • Empty object
    • Non-numeric String
    • undefined/empty variable
    • Array with more than one element
  • Returns 0 if:
    • Empty String
    • Empty Array
    • null

Example 1: Using Math.abs() with Number

// Using Math.abs() with Number
value1 = Math.abs(57);
console.log(value1); // 57

value2 = Math.abs(0);
console.log(value2); // 0

value3 = Math.abs(-2);
console.log(value3); // 2

// Using Math.abs() with numeric non-Number
// single item array
value = Math.abs([-3]);
console.log(value); // 3

// numeric string
value = Math.abs("-420");
console.log(value); // 420

Output

57
0
2
3
420

Example 2: Using Math.abs() with non-Number

// Using Math.abs() with non-Number

// Math.abs() gives NaN for
// empty object
value = Math.abs({});
console.log(value); // NaN

// non-numeric string
value = Math.abs("Programiz");
console.log(value); // NaN

// undefined
value = Math.abs(undefined);
console.log(value); // NaN

// Array with >1 items
value = Math.abs([1, 2, 3]);
console.log(value); // NaN

// Math.abs() gives 0 for
// null objects
console.log(Math.abs(null)); // 0

// empty string
console.log(Math.abs("")); // 0

// empty array
console.log(Math.abs([])); // 0

Output

NaN
NaN
NaN
NaN
0
0
0