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

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

    What MIGHT be lost here (not direct with your example) is that you can then have a tri-state object:

    var myfunc = function(testparam) {
        if (typeof testparam === 'undefined') return;
        if (testparam) {
            return true;
        }
        else {
            return false;
        }
    };
    
    var thefirst = myfunc(true)
    var thesecond = myfunc(false);
    var thelast = myfunc();
    alert("type:" + typeof thefirst+" value:"+thefirst);
    alert("type:" + typeof thesecond+" value:"+thesecond);  
    alert("type:" + typeof thelast+" value:"+thelast); 
    

    these return:

    > type:boolean:true 
    > type:boolean:false
    > type:undefined:undefined
    

    note: null would return false in this example myfunc(null);

提交回复
热议问题