Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
How can I rewrite this code using a ternary operator?

The following is a code I have written to change a grid color to indigo upon clicking it, then removing the color upon the second click. However, I do not know how to rewrite the if-else statement using a ternary operator.

const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
    console.log(e);
    if (grid1.style.backgroundColor) {
      grid1.style.backgroundColor = "";
      } else {
        grid1.style.backgroundColor = "indigo";
      }
})

Thank you for your help in advance (:

Update Thanks for the answers! But now I have one more inquiry -- I wanted to try different ways of rewriting the same code, and came up with this:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";

It did exactly what I wanted with the expression (grid1.style.backgroundColor==false), but not in the case of the former. Is there a reason why?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Straightforward translation into a ternary:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo"; 
about 4 years ago · Juan Pablo Isaza Relatório

0

grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'
about 4 years ago · Juan Pablo Isaza Relatório

0

You can try this:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";

Checkout below reference to learn more about ternary operator https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda