How can this return a number between -2 and 2
var number = Math.random() * 4 - 2;
How can this return a number between -2 and 2
var number = Math.random() * 4 - 2;
The method Math.random()
gives you a decimal number between 0 and 1. If it returns, 0.00001, you'll get 0.00001 * 4 - 2 = 0.00004 - 2 = -1.99996
A pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.