In JavaScript, we can easily get a random boolean using the JavaScript Math.random() method along with an if else conditional statement.

var booleanValue;
if ( Math.random() > .5 ){
  booleanValue = true;
} else {
  booleanValue = false;  
}

Being able to generate random numbers efficiently when working with a programming language is very important. In JavaScript, we can generate a random number easily to get random boolean values.

To get a boolean randomly, we can use the JavaScript Math.random() method.

The random() method will generate a random float between 0 and 1. We can then put this in an if else condition statement. If the value is greater than .5 (50% chance of this), then we return true. If not, we return false.

Below is an example of how to get a boolean value randomly in JavaScript.

var booleanValue;
if ( Math.random() > .5 ){
  booleanValue = true;
} else {
  booleanValue = false;  
}

console.log(booleanValue);

#Output:
True

One such application of generating random boolean values would be if you wanted to generate a coin flip in JavaScript.

Below is some sample code of how you could flip a coin in JavaScript.

var headsOrTails;
if ( Math.random() > .5 ){
  headsOrTails = "Heads";
} else {
  headsOrTails = "Tails";
}

Using JavaScript to Generate a List of Random Booleans in a Loop

If you want to generate a list of random booleans, we can easily define a function and use a loop in JavaScript.

In this example, we will create a function that takes one argument, the number of booleans you want to create, and will return a list of random booleans.

Below is some sample code that will get the random booleans for you in JavaScript.

function randomBooleans(n){
  var bools = [];
  for ( var i = 0; i < n; i++ ){
    if ( Math.random() > .5 ){
      bools[i] = true;
    } else {
      bools[i] = false;  
    }
  }
  return bools;
};

console.log(randomBooleans(10));

#Output:
[True, True, False, True, True, False, True, True, False, True]

Generating a Random Boolean With Probability

In the examples above, we’ve been assuming that we want to have 50% True and 50% False generated from our JavaScript program.

If we want to create a random boolean based on probability, we can use the Math.random() method and adjust the threshold.

For example, if we want to generate True 70% of the time, then we would do the following in JavaScript:

var booleanValue;
if ( Math.random() > .7 ){
  booleanValue = true;
} else {
  booleanValue = false;  
}

Hopefully this article has been helpful for you to learn how to get a random boolean in JavaScript.

Categorized in:

JavaScript,

Last Update: March 14, 2024

Tagged in: