Explain Codes LogoExplain Codes Logo

Js generate random boolean

javascript
randomness
boolean
math.random
Anton ShumikhinbyAnton Shumikhin·Feb 27, 2025
TLDR

To randomly generate a boolean with a 50/50 chance of getting true or false, use Math.random() < 0.5:

const randomBool = Math.random() < 0.5; // Like flipping a coin, but without the actual coin

This bit of magic takes advantage of the Math.random() function, which conjures up a number in the range 0 to <1, giving you a fifty-fifty shot at true or false.

Adjusting the odds

Want to play with the odds? No problem! Adjust the fixed number to tweak the ratio of true vs false:

const likelyTrue = Math.random() < 0.75; // Now 'true' has a 75% chance. Almost as predictable as a sneeze during allergy season!

And lodash can do this job too:

const randomBool = _.sample([true, false]); // lodash chooses true or false like choosing ice cream flavors!

Secure random booleans

When the stakes are higher and security matters, crypto.getRandomValues() is your ally:

const secureRandomBool = (crypto.getRandomValues(new Uint8Array(1))[0] & 1) === 1; // Now that's a secret bool. James Bond way!

Best practices for AI

For AI-related algorithms, where deterministic randomness is key, your solution will keep your AI on its toes:

var AIrandomBool = () => Math.random() < 0.5; // Unpredictable as the ending of a good movie!

Keep it simple with Math.round

For those who cherish simplicity, here's a delightful scenic route, in case you insist on getting lost:

var randomBoolean = !Math.round(Math.random()); // Round and around we go, true or false? Nobody knows!

Efficient use cases

Performance and readability matter. Here're some examples of incorporating randomness elegantly in your JS scripts:

// Quick decisions in conditions const direction = Math.random() < 0.5 ? 'left' : 'right'; // Left or right? JavaScript, make the choice for me! // Frequent use within loops for(let i = 0; i < 10; i++) { if(getRandomBool()) doSomething(); } // My life's like a loop, repeating the same choices over and over. // Node.js secure randomness const crypto = require('crypto'); const randomBoolean = crypto.randomInt(0, 2) === 1; // As unpredictable as next year's Oscar's best picture! // Dynamic interfaces, like toggling a CSS class element.classList.toggle('active', Math.random() < 0.5); // Ever seen a website that changes color when you blink? You've got the power! // Randomness in game events if (Math.random() < 0.25) { spawnExtraLife(); } // I've mastered the art of appearing out of thin air!