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

前端 未结 5 654
滥情空心
滥情空心 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:38

    Using return without a value will return the value undefined.

    If the value is evaluated as a boolean, undefined will work as false, but if the value for example is compared to false, you will get a different behaviour:

    var x; // x is undefined
    alert(x); // shows "undefined"
    alert(!x); // shows "true"
    alert(x==false); // shows "false"
    

    So, while the code should logically return true or false, not true or undefined, you can't just change return; to return false; without checking how the return value is used.

提交回复
热议问题