Get a random boolean in JavaScript
11 March 2022 (Updated 17 May 2022)
I was just working on a coding challenge on Codewars where I needed to randomly set the characters of a given string to either uppercase or lowercase.
This required coming up with some means of randomly setting a character ‘s casing so a quick StackOverflow search gave me this nifty little trick:
Math.random() >= 0.5
This works because Math.random()
returns a random float between 0 and 1. So the probability of that random number being 0.5 or above is roughly 50%.
Here is my final solution to the challenge:
const randomCase = str => {
return str
.split('')
.map(char =>
Math.random() >= 0.5 ? char.toUpperCase() : char.toLowerCase()
)
.join('')
}
It would be nice if JavaScript had a native API for this. Perhaps something like:
Random.boolean()
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment