How to decide between two numbers randomly using javascript?

JavascriptRandom

Javascript Problem Overview


I want a javascript script that choose either value1 or value2 randomly, not between the two values , just the actual values.

Thanks!!!!

Javascript Solutions


Solution 1 - Javascript

The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.

var chosenValue = Math.random() < 0.5 ? value1 : value2;

Solution 2 - Javascript

Math.round(Math.random()) returns a 0 or a 1, each value just about half the time.

You can use it like a true or false, 'heads' or 'tails', or as a 2 member array index-

['true','false'][Math.round(Math.random())] will return 'true' or 'false'...

Solution 3 - Javascript

~~(Math.random()*2) ? true : false

This returns either 0 or 1. "~~" is a double bitwise NOT operator. Basically strips the the decimal part. Useful sometimes.

It is supposed to be faster then Math.floor()

Not sure how fast it is as a whole. I submitted it just for curiosity :)

Solution 4 - Javascript

parseInt(Math.random() * 2) ?  true : false;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMidnightCoderView Question on Stackoverflow
Solution 1 - JavascriptPeter OlsonView Answer on Stackoverflow
Solution 2 - JavascriptkennebecView Answer on Stackoverflow
Solution 3 - JavascriptTomView Answer on Stackoverflow
Solution 4 - JavascriptOscar ArturoView Answer on Stackoverflow