How to Generate a Random Boolean using JavaScript?
Last Updated :
09 Oct, 2024
Improve
To generate a random boolean in JavaScript, use Math.random(), which returns a random number between 0 and 1.
Approach: Using Math.random() function
- Calculate Math.random() function.
- If it is less than 0.5, then true otherwise false.
Example 1: This example implements the above approach.
// Function to generate and log a random boolean value
function generateRandomBoolean() {
console.log(Math.random() >= 0.5);
}
// Simulate a button click by calling the function
generateRandomBoolean();
// Function to generate and log a random boolean value
function generateRandomBoolean() {
console.log(Math.random() >= 0.5);
}
// Simulate a button click by calling the function
generateRandomBoolean();
Output
false
Example 2:
- Create an array containing 'true' and 'false' values.
- Calculate Math.random() and round its value.
- Use rounded value as the index to the array, to get boolean.
// Array containing true and false
let ar = [true, false];
// Function to generate and log a random boolean
function generateRandomBoolean() {
let index = Math.round(Math.random());
console.log(ar[index]);
}
// Simulate a button click by calling the function
generateRandomBoolean();
// Array containing true and false
let ar = [true, false];
// Function to generate and log a random boolean
function generateRandomBoolean() {
let index = Math.round(Math.random());
console.log(ar[index]);
}
// Simulate a button click by calling the function
generateRandomBoolean();
Output
true