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

118
Visualizações
Strangest JS ternary statement I've ever seen

So i'm working on this project, which has code someone else wrote, and I found this javascript ternary operation to assign a variable. They aren't available for me to ask about it. I understand the first half, but ...

variable = statement ? option1 : option2 ? option2 : option1

it would be simple for me if it was just

variable = statement ? option1 : option2

but the second half of the statement is just baffling to me. Can someone please explain what is happening here?

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

0

variable = statement ? option1 : option2 ? option2 : option1

is, spaced out:

variable = statement
  ? option1
  : option2
    ? option2
    : option1

If statement, option1.

Otherwise, if option2, option2.

Otherwise, option1.

Another way of doing it is:

if (statement) {
  variable = option1;
} else if (option2) {
  variable = option2;
} else {
  variable = option1;
}

A clearer way of implementing the same logic would be:

if (!statement && option2) {
  variable = option2;
} else {
  variable = option1;
}

or

variable = (!statement && option2)
  ? option2
  : option1;
about 4 years ago · Juan Pablo Isaza Relatório

0

Not the same.
variable = statement ? option1 : option2 ? option2 : option1
would be the equivalent of -

if (statement) {
   variable = option1;
} else {
   if (option2) {
      variable = option2;
   } else {
      variable = option1;
   }
}

Where as
variable = statement ? option1 : option2
would be equivalent to -

if (statement) {
   variable = option1;
} else {
   variable = option2;
}

As can be more clearly seen here, in the second example, if statement is false, variable will always be equal to option2.
But in the first example, it can still be equal to option1 in some cases.

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