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

时间:2012-02-24 18:02:01

标签: javascript

假设您有两个相同的函数,它们不返回值

function a() {
    // do some interesting things
}

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

函数b显然更冗长,但它们之间是否有任何功能差异?

3 个答案:

答案 0 :(得分:10)

没有真正的区别;两者都将返回undefined

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


要自行确认,您可以运行此代码 - FIDDLE

​function a() {
}

function b() {
    return;
}

var aResult = a();
var bResult = b();

alert(aResult === bResult);  //alerts true

答案 1 :(得分:3)

亚当是正确的;这两个函数都返回undefined,如果你不关心返回值(或者希望值未定义),这两种方法都是绝对正确的。但是,在更复杂的程序中,从函数显式返回通常更好,特别是因为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();

答案 2 :(得分:1)

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

function b() {
  return 'hello';
}

a = b();

console.log(a);

将“hello”输出到您的控制台。