Is there a benefit to using a return statement that returns nothing?

前端 未结 5 657
滥情空心
滥情空心 2020-12-13 02:00

I\'m refactoring a large javascript document that I picked up from an open source project. A number of functions use inconsistent return statements. Here\'s a simple examp

5条回答
  •  一向
    一向 (楼主)
    2020-12-13 02:46

    "Blank return" statements can be used to transfer the control back to the calling function (or stop executing a function for some reason - ex: validations etc). In most cases I use blank return statement is when I'm doing some kind of a validation. However, I make it a point to set some indicator as to why the execution of the function is stopped. For example, set the "innerText" property on a DIV element with the error message.

    In the code above, it looks like it is a validation. The function returns a "true" if everything went well. It looks like the calling function parses the return value, and if it is "true", next step of statements (in the calling function) are executed.

    It is a good practice to return "false" instead of a blank return in the above example. That way you make it all uniform and make life easy for other programmers.

    You could fix such inconsistencies; however, make sure you test all the changes thoroughly. It is a good practice to test each change you make to the code, however small it may be.

提交回复
热议问题