snippetjavascriptTip
Generate a random boolean value in JavaScript
Viewed 0 times
javascriptvaluegeneraterandomboolean
Problem
JavaScript doesn't have a built-in function to generate a random boolean value, but you can easily create one using
As
Math.random(). All you need to do is check if the result of Math.random() is greater than or equal to 0.5.As
Math.random() generates a random number between 0 and 1, the probability of the result being greater than or equal to 0.5 is 50%, which makes for an even distribution of true and false values.Solution
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean(); // trueCode Snippets
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean(); // trueContext
From 30-seconds-of-code: random-boolean
Revisions (0)
No revisions yet.