In JavaScript, we can simulate a coin flip and get a random result using the JavaScript Math.random() method along with an if else conditional statement.
var headsOrTails;
if ( Math.random() > .5 ){
headsOrTails = "Heads";
} else {
headsOrTails = "Tails";
}
Being able to generate random numbers efficiently when working with a programming language is very important. In JavaScript, we can generate random numbers easily to get a coin flip.
To get a coin flip, we can use the JavaScript Math.random() method.
The random() method will generate a random float between 0 and 1. We can then put this in an if else condition statement. If the value is greater than .5 (50% chance of this), then we return “Heads”. If not, we return “Tails”.
Below is an example of how to get a coin flip in JavaScript.
var headsOrTails;
if ( Math.random() > .5 ){
headsOrTails = "Heads";
} else {
headsOrTails = "Tails";
}
console.log(headsOrTails);
#Output:
Heads
In this example, we’ve explicitly returned “Heads” or “Tails, but this could easily be changed if you just want a random boolean.
Using JavaScript to Flip Coins in a Loop
If you want to generate a list of coin flips, we can easily define a function and use a loop in JavaScript.
In this example, we will create a function that takes one argument, the number of flips you want to do, and will return a list of coin flips.
Below is some sample code which will flip coins for you in JavaScript.
function coinFlip(n){
var flips = [];
for ( var i = 0; i < n; i++ ){
if ( Math.random() > .5 ){
flips[i] = "Heads";
} else {
flips[i] = "Tails";
}
}
return bools;
};
console.log(coinFlip(10));
#Output:
['Tails', 'Tails', 'Heads', 'Tails', 'Heads', 'Tails', 'Heads', 'Tails', 'Tails', 'Heads']
Hopefully this article has been helpful for you to learn how to do a coin flip in JavaScript.