Search code examples
javascriptif-statementstring-comparisontic-tac-toe

Is there any mistake in comparing strings in JS?


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


Solution

  • 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)) {
    ...