EN
JavaScript - random boolean value
9
points
In this short article, we would like to show to randomize boolean value using JavaScript.
Quick solution:
const value = Math.random() < 0.5;
Solution explaination
Math API method returns random values from 0
(inclusive) up to 1
(exclusive). Comparing that random value using < 0.5
condition we get true
/false
values with equals probability (50%
/50%
).
Reusable function
In this section you can find function that returns true
/false
values with equals probability (50%
/50%
).
// ONLINE-RUNNER:browser;
const randomBoolean = () => Math.random() < 0.5;
// Usage example:
console.log(randomBoolean()); // false
console.log(randomBoolean()); // true
console.log(randomBoolean()); // true
Random function (with probability)
In this section you can find function that returns true
values with indicated probability (from 0.0
to 1.0
).
// ONLINE-RUNNER:browser;
const randomBoolean = (probability = 0.5) => Math.random() < probability;
// Usage example:
console.log(randomBoolean(0.0)); // 0% chance to randomize true
console.log(randomBoolean(0.2)); // 20% chance to randomize true
console.log(randomBoolean(0.5)); // 50% chance to randomize true
console.log(randomBoolean(0.8)); // 80% chance to randomize true
console.log(randomBoolean(1.0)); // 100% chance to randomize true