Checking for boolean value – Javascript

I’m coding a simple game in pure Javascript and have the boolean which should tell me if I have two or one player (vs computer), but in both cases I get either two players to play or vs computer.

Here is the code:

 var computer = true; // true should be default
 
 // Click listener to change the value
 twoPlayer.addEventListener("click", function() {
    // styling code
    computer = !computer;
 });
 
 
 if(computer == true) {
     // code
 } else {
     // code
 }

I haven’t been working in pure JS till now, I read a lot of questions about boolean but nothing helps.

Answer

If your code really is as shown, computer will be true as of the check, because the check is done immediately; there’s no possibility of the event handler having fired.

You’ll need to check computer later, after the event may have fired, in order to see changes made to computer by your handler. You’d probably do that in response to another event, such as the user saying “start a game”:

var computer = true;
document.getElementById("twoPlayer").addEventListener("click", function() {
  computer = !computer;
  console.log("toggled to " + computer);
});

document.getElementById("start").addEventListener("click", function() {
  if (computer) {
    console.log("Start game against the computer");
  } else {
    console.log("Start two-player game");
  }
});
<input id="twoPlayer" type="button" value="Toggle Two-Player Mode"> <input id="start" type="button" value="Start Game">

But, depending on what twoPlayer is, you may not need an event handler for it at all. If it’s a checkbox, for instance, you can leave it to maintain its own state and just check that state when you need it:

document.getElementById("start").addEventListener("click", function() {
  var twoPlayer = document.getElementById("twoPlayer");
  if (twoPlayer.checked) {
    console.log("Start two-player game");
  } else {
    console.log("Start game against the computer");
  }
});
<label>
  <input id="twoPlayer" type="checkbox"> Two player
</label>
<input id="start" type="button" value="Start Game">

Side note: There’s no need for == true in your comparison, just if (computer) is sufficient (or if you’re checking the negative, if (!computer)).

Leave a Reply

Your email address will not be published. Required fields are marked *