有return语句和没有return语句的函数之间有区别吗

Is there a difference between a function with and without a return statement?

本文关键字:语句 return 有区别 之间 函数      更新时间:2023-09-26

假设有两个相同的函数不返回值

function a() {
    // do some interesting things
}
function b() {
    // do the same interesting things
    return;
}

函数b显然更详细,但它们之间有什么功能区别吗?

没有真正的区别;两者都将返回CCD_ 2。

没有return语句的函数将返回undefined,带有空return语句的函数也将返回。


要自己确认这一点,您可以运行以下代码--FIDDLE:

​function a() {
}
function b() {
    return;
}
var aResult = a();
var bResult = b();
alert(aResult === bResult);  //alerts true

Adam是正确的;这两个函数都返回未定义的值,如果您不关心返回值(或者希望值未定义),那么无论哪种方式都是完全可以的。然而,在更复杂的程序中,从函数显式返回通常更好,特别是因为Javascript程序通常具有复杂的回调机制。例如,在这段代码中(只是比您的代码稍微复杂一点),我相信return语句确实有助于澄清代码:

function someAsyncFunction(someVar, callback) {
    // do something, and then...
    callback(someVar);
    // will return undefined
    return;
}
function c(){
    var someState = null;
    if (some condition) {
        return someAsyncFunction(some variable, function () {
            return "from the callback but not the function";
        });
        // we've passed the thread of execution to someAsyncFunction
        // and explicitly returned from function c.  If this line
        // contained code, it would not be executed.
    } else if (some other condition) {
         someState = "some other condition satisfied";
    } else {
         someState = "no condition satisfied";
    }
    // Note that if you didn't return explicitly after calling
    // someAsyncFunction you would end up calling doSomethingWith(null)
    // here.  There are obviously ways you could avoid this problem by
    // structuring your code differently, but explicit returns really help
    // avoid silly mistakes like this which can creep into complex programs.
    doSomethingWith(someState);
    return;
}
// Note that we don't care about the return value.
c();

通常您会返回一个值。例如,

function b() {
  return 'hello';
}
a = b();
console.log(a);

将向您的控制台输出"你好"。