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.
Syntax
Math.abs(param);
Parameter
param: This is the input value of typeNumberfor which we want to find theabs().
Numberin JavaScript is a 64-bit double-precision value which is the same asdoublein C# or Java.
Return value
-
Number: It returns the absolute value of the givenparam. Ifparamis negative, it returns positiveparam, and returns the same ifparamis already positive. -
NaN: The function returnsNaNifparamis one of the following:- Empty object
- Non-numeric string
- Undefined / empty variable
- Array with more than one member
-
0: The function returns this ifparamis 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([]));