I'm writing a function that calls other functions until one of them returns a "not false" value. This value should be returned by the main function. What is the shortest manner of rewriting this function so it doesn't call the other functions twice, and - if possible - avoiding using an extra variable?
function doSomething(){
if (tryA()) return tryA();
if (tryB()) return tryB();
if (tryC()) return tryC();
return screwIt();
}
You could use the ternary operator:
return tryA() ?: (tryB() ?: (tryC() ?: screwIt()));
Demo on 3v4l.org
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