Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Say you have 2 identical functions that do not return a value

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

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

Function b is obviously more verbose but is there any functional difference between these?

like image 920
Matt Campbell Avatar asked Feb 24 '12 18:02

Matt Campbell


2 Answers

There's no real difference; both will return undefined.

Functions with no return statement will return undefined, as will functions with an empty return statement.


To confirm this for yourself, you can run this code -- FIDDLE:

​function a() {
}

function b() {
    return;
}

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

alert(aResult === bResult);  //alerts true
like image 95
Adam Rackis Avatar answered Nov 15 '22 00:11

Adam Rackis


Adam is correct; both functions return undefined, and either way is absolutely fine if you don't care about the return value (or desire the value to be undefined). However, it's often better in more complex programs to explicitly return from a function, especially since Javascript programs often have complex callback mechanisms. For example, in this piece of code (just a little more complex than yours) I believe the return statement really helps clarify the code:

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();
like image 35
mattbornski Avatar answered Nov 14 '22 22:11

mattbornski