Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use condition of if statement as return value

I have a function that returns either false or a number other than 0. Now I’m calling this function in another function to conditionally return the number.

function falseOrNumber() { ... }

function otherFunction() {
    // ...
    if (falseOrNumber()) return falseOrNumber()
    // ...
}

Now I was wondering, if there is an elegant way to perform this in one line without calling falseOrNumber() twice.

So I’m not looking for the obvious solution:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let i = falseOrNumber()
if (i) return i

This is nothing game changing, but I’ve encountered similar situations several times in the past and I’d like to know if there is a cleaner way.

>Solution :

If you assign the return value of the function to a variable inside the if statement, you can re-use it with the return statement:

function falseOrNumber() { ... }

function otherFunction() {
    // ...
    let result;
    if(result = falseOrNumber()) return result;
    // ...
}

If you want more elegance, there is probably a way to have one return statement for the entire function, instead of returning early. You can also use a comma expression to turn multiple expressions into a one-liner.

function otherFunction() {
    return falseOrNumber() || (other, code, here);
}

Update: your comment says that you have multiple functions like falseOrNumber. If so, you can do this:

function otherFunction() {
  return falseOrNumber() || somethingElse() || orSomethingElse();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading