Is it valid for a render to have more than one return statement within it?

Question

In the context of this exercise, we have multiple return statements inside of render(), but is this valid?

Answer

Yes, this is valid. Each return statement is nested inside of an if or else code block, meaning that only one of the code blocks will ever run on a render(), and so only one of the several return statements will run. The render() function has no limit to how many of these return statements can be inside of it, but only one will ever run at a time.

12 Likes

I feel this is not entirely complete. You can have multiple return statements, but only the first one that is encountered by the logic, will run. The if/else block is not required.
An if/else is a good way to determine which return statement will run, but you can technically have a bunch of returns sitting on the same level in code, where only the first one will run and the rest will be ignored.

An approach I often use, is:

function checkCondition( myCondition ) {
    if ( true === myCondition ) {
        return 'great success!';
    }
    return 'sad!'
}

So, if the myCondition var is true, the function will return ‘great success!’ and in all other cases it will return ‘sad!’ In this rather simple case, the difference doesn’t seem that big, but in larger, more complex function I’ve found it’s less prone to error if you only strictly test for the specific cases where you want to make a change to the output.

22 Likes

@net6424043546 Your code does the same thing as if/else when we have only two possible outcomes we want to return. But in cases where we have more than two possible outcomes our if/else block is going to be very necessary.

1 Like

Somehow I like this better :smile:

Yes but we are not talking about more than two outcomes. What is the value of your extra comment? Think about it :slight_smile:

you are right you can use as many as return statements you want, but please avoid using this unless you really need it like in the guard clause cases.
I believe it will be hard to debug in big functions that have many return statements and will cause a lot of headaches.

4 Likes