There comes a situation where we need to change a number’s sign (+/-). We can do this in two ways:

Math.abs()

abs gives the absolute number irrespective of a number’s sign.

1
2
3
const randomDiff = Math.abs(Math.random() - Math.random());

console.log(randomDiff);

Math.sign

On the other hand, sign returns the sign of a number as either -1 or 1 or 0 if the number is 0.

1
2
3
4
5
const randomNumber = Math.random() - Math.random();

const randomDiff = Math.sign(randomNumber) * randomNumber;

console.log(randomDiff);