JavaScript random generate 0 or 1 integer

You can use Math.round(Math.random()). If Math.random() generates a number less than 0.5 the result will be 0 otherwise it should be 1.


There is a +1 with Math.random, so it will always going to add 1 to the randomly generated number. You can just randomly generate a number, since Math.random will generate any floating number between 0 & 1, then use if.. else to assign 0 or 1

var y = Math.random();
if (y < 0.5)
  y = 0
else
  y= 1
console.log(y)

Tags:

Javascript