JS generate random boolean JS generate random boolean javascript javascript

JS generate random boolean


You can compare Math.random() to 0.5 directly, as the range of Math.random() is [0, 1) (this means 'in the range 0 to 1 including 0, but not 1'). You can divide the range into [0, 0.5) and [0.5, 1).

var random_boolean = Math.random() < 0.5;

// Exampleconsole.log(Math.random() < 0.1); //10% probability of getting trueconsole.log(Math.random() < 0.4); //40% probability of getting trueconsole.log(Math.random() < 0.5); //50% probability of getting trueconsole.log(Math.random() < 0.8); //80% probability of getting trueconsole.log(Math.random() < 0.9); //90% probability of getting true