Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

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 example of what I mean:

var func = function(param) {
    if (!param) {
        return;
    }
    // do stuff
    return true;
}

Sometimes the functions return boolean, sometimes strings or other things. Usually they are inconsistently paired with a simple return; statement inside of a conditional.

The problem is that the code is complex. It is a parser that uses a multitude of unique RegEx matches, creates and destroys DOM nodes on the fly, etc. Preliminary testing shows that, in the above example, I could change the return; statement to become return false;, but I'm concerned that I may not realize that it had a negative impact (i.e. some feature stopped working) on the script until much later.

So my questions: Is there a benefit to using a blank return statement? Could this have been intentionally coded this way or was it just lazy? Can I change them all to return false;, or return null; or do I need to dig through every call and find out what they are doing with the results of those functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...