You can find the absolute value of a number in JavaScript by using the Math.abs()
method. The absolute value of a number means how far a number is from zero.
Math.abs()
only takes one number
type parameter and return the absolute value of that number:
Math.abs(-5);
Math.abs(5);
// both returns 5
Both the negative number -5
and the positive number 5
is 5
numbers away from zero (so both returns 5
)
When you pass more than one parameter, JavaScript will ignore the rest and operate only on the first:
Math.abs(-3, 5);
Math.abs(-3, "Hello");
// returns 3
When you pass non-number data type, the method will return NaN
as value:
Math.abs("String");
// returns NaN