Coin Flip


#1

I am trying to create a program thar flips a coin and then logs that value to the console. Here is the link: Click here to see the code. I am using html, css, and javascript. If you do not want to go to the link then here is the code.
HTML:

Random Things!

Coin Flip!

Press this button to flip a coin!

Click me to flip a virtual coin!
CSS:
.coinFlip {
text-align: center;
border: 2px solid;
color: #3f6cff;
}
#subtitle {
text-align: center;
size: 20px, 20px;
color: #84069e;
}

.activate {
text-align: ceter;
}
JavaScript:
coins = function() {
let coinflip = Math.Floor(Math.random * 3);
var coin = ‘’;

if (coinflip === 1) {
coin = ‘Heads’;
} else {
coin = ‘Tails’
}
console.log(coin);
}
Thanks for helping!


#2

A coin flip is akin to a binary event. Heads or Tails. The above has two errors, one in syntax, Floor as opposed to floor, and one in logic, * 3 as opposed to * 2.


#3

I fixed those errors and it is not logging to the console. and also how would I have a html tag show the value of that javascript variable


#4

By caching the element node then inserting content with your script.

<p id="outcome"></p>

That can be anywhere in your document. The JS will read,

const outcome = document.querySelector('#outcome');

Declare it at the top of your script. After each flip of the coin,

outcome.textContent = coin;

Be sure your script is imported by the HTML with a <script></script> element at the bottom of the BODY, just above the </body> endtag.


If we want to get a little fancier, we can combine all the logic into that one statement.

outcome.textContent = coinflip ? `Tails` : `Heads`;

Recall that coinflip will be 0 or 1, which equate to falsy and truthy so the ternary is an appropriate control flow device.

Your code would be significantly reduced,

const random = Math.random;
const floor = Math.floor;
const coinToss = () => {
    outcome.textContent = floor(random * 2) ? `Tails` : `Heads`;

Your HTML could have a button so the user can flip at will.

<button>Flip Coin</button>

and the cached element node would be,

const flipCoin = document.querySelector('button');

At the end of your script, add a listener for which coinToss will be the handler function.

flipCoin.onclick = coinToss;

An alternative to the ternary expression is an array…

outcome.textContent = ['Tails', 'Heads'][floor(random * 2)];