November 6, 2023

You can generate a random boolean in JavaScript using the `Math.random()`

function to produce a value that is then evaluated as true or false. We’ll go into more detail on this below.

## Understanding `Math.random()`

JavaScript's `Math.random()`

function generates a floating-point, pseudo-random number in the range 0 (inclusive) to 1 (exclusive). This means that every time you call `Math.random()`

, you'll receive a new number that could be anything from 0 up to but not including 1.

## Simplest approach: Using `Math.random()`

The most straightforward way to get a random boolean value is by checking if `Math.random()`

is greater than 0.5. Since `Math.random()`

can return any value between 0 and 1, there is a roughly 50/50 chance that the result will be above or below 0.5.

const randomBool = Math.random() >= 0.5;

## Ensuring equal distribution

Although the above method is concise, it may not offer a perfect 50/50 distribution due to the nature of floating-point calculations and the implementation of `Math.random()`

. For most purposes, this isn't a concern, but if an exact distribution is critical, you might want to implement additional checks or a different method.

## Using bitwise operators

Bitwise operators can also be used to generate a random boolean. By using the OR operator with zero, you can convert the generated number to an integer, and the double NOT bitwise operator will then convert this integer to a boolean value.

const randomBool = !!(Math.random() * 2 | 0);

## Generating multiple random booleans

If you need to generate an array of random booleans, you can use the `Array.from`

method in combination with `Math.random()`

.

const randomBools = Array.from({ length: 10 }, () => Math.random() >= 0.5);

This code snippet creates an array with ten random booleans.

## Using a function for readability

For better readability and reusability, you can wrap the random boolean generation in a function.

function getRandomBool() { return Math.random() >= 0.5; }

Now, whenever you need a random boolean, you just call `getRandomBool()`

.

## Customizing probability

If you want to customize the probability of true or false, you can pass a threshold to the function.

function getRandomBool(threshold = 0.5) { return Math.random() < threshold; }

By changing the threshold value, you can adjust the probability that true is returned.

## Other ways to generate a random boolean in JavaScript

### T**he **`Boolean`

constructor

`Boolean`

constructorThis method is useful when you want to make the coercion to boolean very explicit in your code, which can enhance readability for those unfamiliar with JavaScript's truthy and falsy values.

const randomBool = Boolean(Math.floor(Math.random() * 2));

**Toggling a boolean in a loop**

The toggling approach is especially handy in simulations or games where you might want a state to have a chance to change on each iteration, such as flipping a moving character between visible and invisible states to indicate invulnerability.

let bool = false; for (let i = 0; i < 10; i++) { bool = Math.random() >= 0.5 ? !bool : bool; }

**Immediately Invoked Function Expression (IIFE)**

IIFE is suited for situations where you need an immediate execution and there's no need to reuse the code. It keeps the global scope clean and is useful in modular patterns or self-contained components.

const randomBool = (() => Math.random() >= 0.5)();

### T**he **`Date`

object

`Date`

objectUsing the ** Date** object for randomness could be applied in scenarios where the randomness is not critical and might be more about adding slight variability to the behavior of a function. For example, alternating styles or animations in a non-security-related context.

const randomBool = new Date().getMilliseconds() % 2 === 0;

## Conclusion

While there are several ways to generate a random boolean in JavaScript, the simplest method using `Math.random()`

is often sufficient. For more control over the distribution or the probability of true or false, custom functions can be created to suit the specific needs of any project.

# Ship faster, worry less with Basedash

How to Sort Object Array by Boolean Property in JavaScript

Max Musing

How to Truncate Date in MySQL

Max Musing

What is evented I/O for V8 JavaScript?

Max Musing

Replace + with Space in JavaScript

Max Musing

How to Sort JavaScript Objects by Key

Max Musing

How to Scroll Automatically to the Bottom of a Page in JavaScript

Max Musing