Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
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

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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)) {
...
about 4 years ago · Santiago Trujillo Denunciar

0

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda