Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!