Correct function using Math.random() to get 50/50 chance

Math.random():

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)

The random number is either in the range [0,0.5) or [0.5,1). So you should use return Math.random() < 0.5; to have a (theoretical) 50/50 chance.


The first one is the correct because the random number generators returns a number from 0 to 0.99999999 (depends on the exact accuracy of the generator itself)

So by splitting the values into two groups using the "<" operator, you should get two equal ranges:

[0 upto 0.49999999] and [0.5 upto 0.9999999]

Tags:

Javascript