sajad torkamani

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

It would be nice if JavaScript had a native API for this. Perhaps something like:


Tagged: JavaScript

Leave a comment

Your email address will not be published. Required fields are marked *