Boolean expressions

I’m trying to make a Javascript coin toss game and have a question about comparing boolean values.

I have two radio buttons to choose either Heads or Tails, then a play button which runs a function.
The function generates a random decimal number which is rounded up to 1 or down to 0.
0 is assigned to an image of a coin showing heads and 1 to an image showing tails.

I now need to compare the randomly generated number to the radio button selection. If the ‘heads’ radio button is checked then this will evaluate to true, and the number 1 also evaluates to true, but it doesn’t seem to work when I make an if statement comparison in this way to tell the user they have won?

Example code:

if (heads.checked !== random || tails.checked == random) {
winner.innerHTML = "<p>You win!</p>";
} else {
winner.innerHTML = "<p>You lose!</p>";

I’m pretty new to Javascript so any help is appreciated.

just a basic check?

var num = 1;
var check = 1;
if( num == check)
  console.log( "win")
  console.log( "lose") 

Thanks, just wanted to try different ways to solve it but best stick to the basics for now :wink:

Sounds like the right idea. You are using and input with type radio. And generating a random number with Math.random()?
You would have another button I assume to execute the flip?
Then just use an id or whatever selector on the heads radio. Pretty much like you have…

var heads = document.getElementById('heads');
var button = document.getElementById('flip');
var value;

flip.addEventListener('click', (event) => {
      value = Math.round(Math.random());
      if(heads.checked && value === 0) {
           // WINNER 
           // Do cool stuff like show the coin etc
      else if(tails.checked && value === 1) {
            // WINNER AGAIN
      else {
      // LOSER

obviously you want to include some validation. Like making sure that one radio button is always selected, stuff like that.

1 Like