JavaScript: Calculating Absolute Value with Math.abs
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
More JavaScript tutorials
See allJavaScript
Sort Keys in Map Using JavaScript
Dec 11, 2023
JavaScript
Get Element by Data Attribute Using JavaScript
Dec 8, 2023
JavaScript
Convert Milliseconds to Hours Minutes Seconds in JavaScript
Dec 6, 2023
JavaScript
JavaScript Get the Index of Max Value in Array
Nov 16, 2023
JavaScript
JavaScript Check if Value is an Object
Nov 15, 2023