JavaScript has a built-in Math object that includes several handy math-related functions and properties. One such function is abs()
, which returns the absolute value of a number.
In mathematical terms, the absolute value of a number is its distance from zero on a number line. If a number is positive, its absolute value is simply the number itself.
If a number is negative, its absolute value is the same magnitude but with a positive sign. For example, the absolute value of -5 is 5, and the absolute value of 3 is also 3.
The abs()
function can be used with any numerical data type, including floats and integers. It can even be used on complex numbers, though in most cases it’s more practical to use one of JavaScript’s other math functions when working with complex numbers.
To get the absolute value of a number using abs()
, simply pass in the number as an argument:
Math.abs(5); // Returns 5
Math.abs(-5); // Also returns 5