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.

2 Likes