Related Articles
How to generate a random boolean using JavaScript ?
• Last Updated : 12 Sep, 2019

The task is to generate random boolean value. Here we are going to use JavaScript to achieve the goal.

Approach 1:

• Calculate Math.random() function.
• If it is less than 0.5, then true otherwise false.

Example 1: This example implements the above approach.

 ` ``<``html``> `` ` `<``head``> ``    ``<``title``> ``        ``How to generate a random ``        ``boolean using JavaScript?``    ```` `` ` `<``body` `style` `= ``"text-align:center;"` `id` `= ``"body"``> ``     ` `    ``<``h1` `id` `= ``"h1"` `style` `= ``"color:green;"` `> ``        ``GeeksForGeeks ``    ````     ` `    ``<``p` `id` `= ``"GFG_UP"` `style` `= ``        ``"font-size: 15px; font-weight: bold;"``>``    ````     ` `    ``<``button` `onclick` `= ``"gfg_Run()"``> ``        ``Click here``    ````     ` `    ``<``p` `id` `= ``"GFG_DOWN"` `style` `= ``        ``"font-size: 23px; font-weight: bold; color: green; "``>``    ````     ` `    ``<``script``>``        ``var el_up = document.getElementById("GFG_UP");``        ``var el_down = document.getElementById("GFG_DOWN");``         ` `        ``el_up.innerHTML = "Click on the button to "``                        ``+ "generate random boolean.";``         ` `        ``function gfg_Run() {``            ``el_down.innerHTML = Math.random() >= 0.5;``        ``}         ``    `` `` `` ` ``

Output:

• Before clicking on the button:
• After clicking on the button:

Approach 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.

Example 2: This example implements the above approach.

 `  ``<``html``>  `` ` `<``head``> ``    ``<``title``> ``        ``How to generate a random``        ``boolean using JavaScript?``    ```` `` ` `<``body` `style` `= ``"text-align:center;"` `id` `= ``"body"``>  ``     ` `    ``<``h1` `id` `= ``"h1"` `style` `= ``"color:green;"` `>  ``        ``GeeksForGeeks  ``    ````     ` `    ``<``p` `id` `= ``"GFG_UP"` `style` `= ``            ``"font-size: 15px; font-weight: bold;"``>``    ````     ` `    ``<``button` `onclick` `= ``"gfg_Run()"``> ``        ``Click here``    ````     ` `    ``<``p` `id` `= ``"GFG_DOWN"` `style` `= ``        ``"font-size: 23px; font-weight: bold; color: green; "``>``    ````     ` `    ``<``script``>``        ``var el_up = document.getElementById("GFG_UP");``        ``var el_down = document.getElementById("GFG_DOWN");``        ``var ar = [true, false];``         ` `        ``el_up.innerHTML = "Click on the button to "``                        ``+ "generate random boolean.";``     ` `        ``function gfg_Run() {``            ``var index = Math.round(Math.random());``            ``el_down.innerHTML = ar[index];``        ``}         ``    `` ``  `` ` ``

Output:

• Before clicking on the button:
• After clicking on the button:

My Personal Notes arrow_drop_up