HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Generate a random boolean value in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptvaluegeneraterandomboolean

Problem

JavaScript doesn't have a built-in function to generate a random boolean value, but you can easily create one using Math.random(). All you need to do is check if the result of Math.random() is greater than or equal to 0.5.
As Math.random() generates a random number between 0 and 1, the probability of the result being greater than or equal to 0.5 is 50%, which makes for an even distribution of true and false values.

Solution

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

randomBoolean(); // true

Code Snippets

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

randomBoolean(); // true

Context

From 30-seconds-of-code: random-boolean

Revisions (0)

No revisions yet.