April 26, 2021 ‐ 1 min read
Sometimes you may need to turn a negative number into a positive one. Of course there is the high(or elementary?) school mathematics approach: multiplying two negative numbers gives a positive.
let x = -5; x *= -1; console.log(x); // => 5
But this only guarantees a positive number if you are sure that your variable is negative. Otherwise you will a negative and positive number which gives a negative obviously.
In that case you may use the
Math.abs() function returns the absolute value of the number you pass it as a parameter.
If you pass a negative number to
Math.abs() it returns the negation of that number. When you pass it a positive number it returns the number as is, and the same goes for when you pass the number zero.
Math.abs(-5); // => 5 Math.abs(5); // => 5 Math.abs(0); // => 0
Math.abs() you are ensured to have a positive number returned to you.