Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a sort of "conditional return"

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();
}
like image 757
Benedikt Beun Avatar asked Dec 08 '22 11:12

Benedikt Beun


1 Answers

You could use the ternary operator:

return tryA() ?: (tryB() ?: (tryC() ?: screwIt()));

Demo on 3v4l.org

like image 168
Nick Avatar answered Dec 10 '22 00:12

Nick