Home > Blockchain >  Is there any mistake in comparing strings in JS?
Is there any mistake in comparing strings in JS?

Time:07-21

I'm making tic tac toe game and I'm facing issue. If user's input is not equals to X or O then it should print the message Enter correct signs but I have no idea what's wrong in my code. Only else if's block is not working properly.

here is code of that function :

let p1, p2, s1, s2;

function startGame() {
  playAgain();
  p1 = document.getElementById("p1").value;
  p2 = document.getElementById("p2").value;
  s1 = document.getElementById("s1").value;
  s2 = document.getElementById("s2").value;

  if (p1 == "" || p2 == "" || s1 == "" || s2 == "") {
    alert("Enter the details.");
    playAgain();
  } else if (
    s1 != "X" ||
    s1 != "x" ||
    s1 != "O" ||
    s1 != "o" ||
    s2 != "X" ||
    s2 != "x" ||
    s2 != "O" ||
    s2 != "o"
  ) {
    alert("Enter correct signs.");
    playAgain();
  } else {
    alert("You can start the game."   p1   s1   p2   s2);
    isStarted = true;
  }
}

Thank you :D

CodePudding user response:

Try to "and" your conditions instead of "oring" them.

else if (
   (s1 != "X" &&
    s1 != "x" &&
    s1 != "O" &&
    s1 != "o") ||
   (s2 != "X" &&
    s2 != "x" &&
    s2 != "O" &&
    s2 != "o")
  )

I personally would make use of every function to make it even shorter and less repetitive:

const validInputs = ["X", "x", "O", "o"]

else if (validInputs.every((item) => s1 !== item)
      || validInputs.every((item) => s2 !== item)) {
...

CodePudding user response:

It seems line a logic error on the if statement, i tried this and it works properly

if (
    s1 != "X" &&
    s1 != "x" &&
    s1 != "O" &&
    s1 != "o" ||
    s2 != "X" &&
    s2 != "x" &&
    s2 != "O" &&
    s2 != "o"
  ) {

But you also need to validate that s1 isn't equal to s2 because the users can type something like s1='X', s2='x' and it would be valid

  • Related