The absolute value of a number (or a modulus) is the value of a number without its sign, it's always non-negative. For example, the absolute value of number 3.4 is 3.4 and for -5.4 it's 5.4. In mathematics a modulus is usually marked as a number surrounded by two vertical lines:
|-5.4|
There is a special function in JavaScript - Math.abs()
, created for getting an absolute value of a number. All main web browsers support this function: Chrome, Opera, Mozilla, Safari and Edge. Note that this function is a static one which means that you don't need to create any objects of Math
, just use the class name to call it. For example:
number = Math.abs(-5.4);
console.log(number);
// logs 5.4
This function takes only one parameter which is a number whose absolute value we need to get returned.
How it works
Surely Math.abs()
is easy to work with, but do you know how exactly it obtains the absolute value of a number? We can try to check it by simply transforming this function to a string. Let's use the toString()
method to convert this function into a string of characters and see the code. However, console.log(Math.abs.toString())
; will produce the output not that helpful: function abs() { [native code] }
.
Unfortunately, we can't get the native code of this function but with the help of the information we have already found we should be able to create our own method for getting a modulus. The first point is that this function should simply multiply the parameter by -1. But this option does not work for positive numbers as it will simply change it to a negative.
So, we can try to use an if/else
clause or a ternary operator. That is we need to check whether the number is positive or negative. If it's bigger than 0, we return the same number; and if it's less than 0, we return the difference between 0 and this number. Ternary operator ? :
is perfect for this purpose.
function MyAbs(x) {
return (x > 0) ? x : 0 - x;
}
This should work perfectly for numeric values. But what if we pass an array or a string as a parameter? For this case let's add the unary operator + which will help us to convert the parameter into a numeric value.
function MyAbs(x) {
x = +x;
return (x > 0) ? x : 0 - x;
}
console.log( "The absolute value of [-5] is " + MyAbs("[-5]")); // The output: 5
As we see, this code will show us the next output: The absolute value of [-5] is 5.
Where to use
Although the concept of an absolute value is simple, some people can find it completely unnecessary. However, in real life very often we can encounter different situations where negative numbers have no practical sense. For example, we cannot ride "minus 70 miles" (no matter in which direction), nor can we buy "minus 5 kilos" of potatoes.
Essentially, some values must always be positive. That is exactly what we are using an absolute value for. You can also apply this term talking about depth or some approximate values. Math.abs()
is a function perfectly suitable for this case.
Examples
Let's review the results we can get in case of passing different types of parameters into this function.
Example 1. Using numbers.
// Case 1. Using abs() with numbers
number1 = Math.abs(2.5);
console.log('The absolute value of 2.5 is ' + number1); // The output: 2.5
number2 = Math.abs(0);
console.log('The absolute value of 0 is ' + number2); // The output: 0
number3 = Math.abs(-2.5);
console.log('The absolute value of -2.5 is ' + number3); // The output: 2.5
So we can see that if the number is positive, Math.abs()
will return the same number. If it's negative, we will get the opposite one. In case of passing 0 as a parameter, this function will return 0 as well.
Example 2. Using non-numbers.
// Case 2. Using abs() with numeric non-numbers
value1 = Math.abs([-5]); // an array of 1 item
console.log('The absolute value of [-5] is ' + value1); // The output: 5
value2 = Math.abs("-120"); // a numeric string
console.log('The absolute value of "-120" is ' + value2); // The output: 120
This example illustrates that Math.abs()
can return an absolute value of a string of numbers or even an array that consists of one element. Let's see what happens if we use an array with multiple items or a non-numeric string as a parameter.
// Case 3. Using abs() with non-numbers
value1 = Math.abs({}); // an empty object
console.log('The absolute value of an empty object is ' + value1); // The output: NaN
value2 = Math.abs("five"); // a non-numeric string
console.log('The absolute value of five is ' + value2); // The output: Nan
value3 = Math.abs([-1, 0, 1]); // an array with more than 1 element
console.log('The absolute value of [-1, 0, 1] is ' + value3); // The output: NaN
value4 = Math.abs([]); // an empty array
console.log('The absolute value of [] is ' + value4); // The output: 0
value5 = Math.abs(""); // an empty string
console.log('The absolute value of "" is ' + value5); // The output: 0
The output we've got proves that the function returns NaN
, which is a "not-a-number" value, if we pass an empty object (we can also use Object.create(null)
for creating an empty object), a non-numeric string or an array consisting of more than one element.
At the same time this function will return 0 if we pass an empty array or a string with no characters. By the way, if we try to pass a string that shows an array (for example, Math.abs("[-5]")
), this function won't be able to convert it into a numeric value and will return NaN
.
To understand why we get such results we need to dig a little deeper into mathematics. The absolute value of a number is a distance between 0 and a number. Of course the distance can't be negative, that's why the modulus is never less than 0.
We cannot measure the distance between 0 and a word, nor can we find out how far from 0 the empty object is. Empty strings and empty arrays are considered by Math.abs()
as zeros. So there is no distance between them and 0.