I'm wondering if it's possible to access a condition's value directly like the following example.
var a = ["pear", "kiwi", "orange", "apple"]
if(a.indexOf("orange") !== -1){
console.log(this) //as a.indexOf("orange") has been evaluated already above this prints 2
}
This would also make ternary operators less bloaty
var a = ["pear", "kiwi", "orange", "apple"]
var b = ((a.indexOf("orange") !== -1) ? this : '') //"this" equals 2
Thanks
EDIT: Clearing this question up for any future visitors. Basically this question is about retrieving the resulting value of what is evaluated in an if/else statement. In the example of
var a = ["pear", "kiwi", "orange", "apple"]
if(a.indexOf("orange") !== -1){ //is basically if(2 !== -1)
console.log(this) //would then be "2" from the already evaluted a.indexOf from above
}
You can simply store it before the statement if the goal is to not evaluate twice. The answer to your literal question is no.
const orangeIndex = a.indexOf("orange")
if (orangeIndex !== -1) {
console.log(orangeIndex)
}
Same concept applies to the ternary operator.
As others have shown, you can also declare a variable and do the actual assignment in the if statement itself, but IMO this makes your code less readable without adding any value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With