What is Math.abs() in JavaScript?

Math in JavaScript is a built-in object that contains different methods and properties used to perform mathematical operations. It contains an abs() function, which is used to compute a specified number’s absolute value. Absolute value is the number without a sign.

abs() function

Syntax

Math.abs(param);

Parameter

  • param: This is the input value of type Number for which we want to find the abs().

Number in JavaScript is a 64-bit double-precision value which is the same as double in C# or Java.

Return value

  • Number: It returns the absolute value of the given param. If param is negative, it returns positive param, and returns the same if param is already positive.

  • NaN: The function returns NaN if param is one of the following:

    • Empty object
    • Non-numeric string
    • Undefined / empty variable
    • Array with more than one member
  • 0: The function returns this if param is one of the following:

    • Null
    • Empty string
    • Empty array

Example

console.log("abs('-1') = " + Math.abs('-1'));
console.log("abs(-1) = " + Math.abs(-1));
console.log("abs([1]) = " + Math.abs([-1]));
console.log("abs('educative') = " + Math.abs('educative'));
console.log("abs() = " + Math.abs());
console.log("abs([1,-1]) = " + Math.abs([1,-1]));
console.log("abs({}) = " + Math.abs({}));
console.log("abs(null) = " + Math.abs(null));
console.log("abs('') = " + Math.abs(''));
console.log("abs([]) = " + Math.abs([]));

Free Resources