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.
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")