Randomly return a true or false from a JavaScript function

It's easy using a ternary expression; once you understand how this is done, many other paths to explore open up

By: Ajdin Imsirovic 07 January 2021

We’ll again use Math.random() for this exercise. Since it returns a value of 0 to 0.99 (both inclusive), all we need to do is have a condition that checks if the Math.random() value is under a certain number.

Thumb up thumb down collage photo

If we want to have Math.random() return true and false with equal chance, we need to split the condition at about 0.5.

For example:

const randomBool = Math.random() > 0.5 ? true : false;

In the above code, we are assigning the result of a ternary statement into randomBool variable.

Let’s see how it works by replacing it with a value:

function testIt() {
    const randomBool = 0.6 > 0.5 ? "It is true" : "It is false";

In the testIt function decalaration, we’ve replaced Math.random() with 0.6. So, 0.6 > 0.5 is true. Because it is indeed true that 0.6 > 0.5, the testIt() function call will return the sentence “It is true”.

Thus, we can conclude that whenever the condition we’re testing in the ternary, i.e whenever the ternary test passes, we’ll get back the value on the left of the :. As a corollary, if the test doesn’t pass, we’ll get back whatever we stored in the value on the right-hand side of the : character.

In other words, looking at this code:

const randomBool = Math.random() > 0.5 ? true : false;

If Math.random() returns a value larger than 0.5, the true boolean value is saved into randomBool. Otherwise, the false value is saved.

That’s it for this example. Only a small reminder should be added here. If we want to have not a 50-50 chance of true appearing, but instead only a 10% chance for getting back the true boolean, and a 90% chance for getting back the false boolean, we simply change the value we’re testing for, from 0.5 to 0.1, like this:

const randomBool = Math.random() > 0.1 ? true : false;

With the above code, we have a 90 percent chance of storing the value false inside the randomBool.

As a final side-note, we actually don’t even have to use a ternary here. It’s enough to test it like this:

const randomBool = Math.random() > 0.5;

While a ternary statement allows for much more flexibility, if we just want to return a true or false, the above code is enough.

So, where’s the flexibility in the ternary statement? We could for example, do this:

const randomBool = Math.random() > 0.5 ? itIsTrue() : itIsFalse();

Additionally, the ternary statement helps us influence the likeliness of the outcome, e.g:

const randomBool = Math.random() > 0.1 ? itIsTrue() : itIsFalse();

These things are not possible with a simple true or false test that looks like this:

const randomBool = Math.random() > 0.5;

This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.

Feel free to check out my work here: