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

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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