Languages
[Edit]
EN

JavaScript - random boolean value

9 points
Created by:
Wiktor-Sribiew
860

In this short article, we would like to show to randomize boolean value using JavaScript.

Quick solution:

const value = Math.random() < 0.5;

 

Solution explaination

Math API method returns random values from 0 (inclusive) up to 1 (exclusive). Comparing that random value using < 0.5 condition we get true/false values with equals probability (50%/50%).

 

Reusable function

In this section you can find function that returns true/false values with equals probability (50%/50%).

// ONLINE-RUNNER:browser;

const randomBoolean = () => Math.random() < 0.5;


// Usage example:

console.log(randomBoolean());  // false
console.log(randomBoolean());  // true
console.log(randomBoolean());  // true

 

Random function (with probability)

In this section you can find function that returns true values with indicated probability (from 0.0 to 1.0).

// ONLINE-RUNNER:browser;

const randomBoolean = (probability = 0.5) => Math.random() < probability;


// Usage example:

console.log(randomBoolean(0.0));  //   0% chance to randomize true
console.log(randomBoolean(0.2));  //  20% chance to randomize true
console.log(randomBoolean(0.5));  //  50% chance to randomize true
console.log(randomBoolean(0.8));  //  80% chance to randomize true
console.log(randomBoolean(1.0));  // 100% chance to randomize true

 

See also

  1. JavaScript - random byte value

  2. JavaScript - random short value

  3. JavaScript - random int value

  4. JavaScript - random long value

Alternative titles

  1. JavaScript - random bool value
  2. JavaScript - random true/false value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join