Should avoid / minimize the use of return statements in javascript flow control

In the current software I'm working on, I see this pattern quite widely, and it seems like they are trying to avoid return statements as much as possible. Even in some places in the code, this is done almost to the extreme.

I once heard for a long time that returning statements should be minimized or avoided, but I cannot remember (or search) for the exact cause or origin of this line of thought. I believe this is due to some performance implications in some PLs.

I personally do not adhere to this, since it does not make the code readable, but, giving it the opportunity to doubt, I am curious whether using this template has its advantages in javascript in terms of performance.

if (err) { if (err.message) { message = err.message; } else { if (err.errorCode) { message = err.errorCode; } else { message = "Unknown error"; } } } else { message = "Unknown error."; } deferred.reject(message); 

If I decided, I would accidentally use the return statement to end the sequence as follows:

 if(!err || (!err.message && !err.errorCode)){ deferred.reject("Unknown error."); return; } if(err.message){ deferred.reject(err.message); return; } if(err.errorCode){ deferred.reject(err.errorCode); } 

Are there any advantages in the first template over the second?

+5
source share
1 answer

Your code example also has an alias - the Christmas tree, and in real projects it is extremely difficult to maintain such a code. For example, you need to add another condition - you put another if block inside an existing one, etc. etc., and it will be a nightmare ... and as a result you will have an awfull tree ...

Alternatively, you can do something like this:

 if (err) { if (err.message) { return err.message; } if (err.errorCode) { return err.errorCode; } } return "Unknown error."; 

Such code looks simpler, right?
So, I really think that for such purposes it makes sense to use return .

BUT, I think the main point here is not to lose consistency ! In our example, we always return the result to the same data type and with the same business logic and, for example:

 if (err) { if (err.message) { return err; } // Here some stuff... // Few lines of code... // return -1; } // Another code... // if (!user) { return null; } // And somewhere in the end on anothere scrollin screen // return user.email; 

this example returns object or number or null or string - and this is another nightmare ...
And in real projects in large functions, it is really easy to get such a code due to the return of the batch ...
So, it’s better to have fewer returns, again because it’s easy to maintain ...

+2
source

Source: https://habr.com/ru/post/1269801/


All Articles