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

178
Vistas
javascript when using multiple if conditions get the failure reason

Over the years there have been multiple answers to this question, evolving from some clunky code.

In 2022 is there a one liner or improved way to get the condition that failed in a multiple if scenario?

example one, myVarTwo fails

if (( myVarOne == "alpha") && ( myVarTwo == "beta") &&  ( myVarThree == "cappa"){
 // do stuff
 }else{
  console.log("failed at ...)
 }

example two, myVarThree fails

if (( myVarOne == "alpha") && (( myVarTwo == "beta") ||  ( myVarThree == "cappa")){
 // do stuff
 }else{
  console.log("failed at ...)
 }

I am assuming the conditions test stops at the first fail.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Firstly, your assumption that the condition test stops at the first fail is correct. The logical && operator is a short-circuit operator. It will return at the first instance of a falsy evaluation. Conversely, the || opearator returns at the first instance of a truthy evaluation.

With that said, my only guess would be to use ternary operators but I'm not sure if you would consider it to be a one liner. Especially if you have a lot more conditions to check for, the ternary operator would get really really long and not very readable. The ternary operators can be seen as simulating multiple if...else conditions being tested sequentially, with an action for each check.

const myVarOne = "alpha",
  myVarTwo = "notBeta",
  myVarThree = "cappa"

const printFailure = (string) => {
  console.log(`Failed at ${string}`)
}

const printSuccess = () => {
  console.log('All conditions satisfied!')
}

// Method 1
myVarOne != "alpha" ? printFailure("myVarOne") : myVarTwo != "beta" ? printFailure("myVarTwo") : myVarThree != "cappa" ? printFailure("myVarThree") : printSuccess()

// Method 2
myVarOne == "alpha" ? myVarTwo == "beta" ? myVarThree == "cappa" ? printSuccess() : printFailure("myVarThree") : printFailure("myVarTwo") : printFailure("myVarOne")

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