JS generate random boolean
!Math.round(Math.random());
If your project has lodash
then you can:
_.sample([true, false])
Alternatively you can use your own sample function (source):
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
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;
// Example
console.log(Math.random() < 0.1); //10% probability of getting true
console.log(Math.random() < 0.4); //40% probability of getting true
console.log(Math.random() < 0.5); //50% probability of getting true
console.log(Math.random() < 0.8); //80% probability of getting true
console.log(Math.random() < 0.9); //90% probability of getting true
For a more cryptographically secure value, you can use crypto.getRandomValues
in modern browsers.
Sample:
var randomBool = (function() {
var a = new Uint8Array(1);
return function() {
crypto.getRandomValues(a);
return a[0] > 127;
};
})();
var trues = 0;
var falses = 0;
for (var i = 0; i < 255; i++) {
if (randomBool()) {
trues++;
}
else {
falses++;
}
}
document.body.innerText = 'true: ' + trues + ', false: ' + falses;
Note that the crypto
object is a DOM API, so it's not available in Node, but there is a similar API for Node.