How to easily get a random boolean in JavaScript

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
    .map(char =>
      Math.random() >= 0.5 ? char.toUpperCase() : char.toLowerCase()

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: