How to easily get a random boolean in JavaScript
July 19, 2020 (Updated April 13, 2021)
I was just doing a coding challenge on Codewars where I had 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('')
}
Tagged:
JavaScript