DSK
DSK

Reputation: 13

The "return" statement

I had a question about the return statement that is by itself in the control flow.

var rockPaperScissors = function(n) {  
    var rounds = n;
    var results = [];

    var weapons = ['rock', 'paper', 'scissors'];

    var recurse = function(roundsLeft, played) {
        if( roundsLeft === 0) {
            results.push(played);
            return;
        }

        for(var i = 0; i<weapons.length; i++) {
            var current = weapons[i];
            recurse( roundsLeft-1, played.concat(current) );
        }
    };

    recurse(rounds; []);
    return results;
}

I was wondering why the return statement is not written as:

return results.push(played);

Is there any benefits? If so, why and when should you write it that way?

Upvotes: 0

Views: 58

Answers (2)

Domysee
Domysee

Reputation: 12846

return; is the same as return undefined;, so basically return nothing.
It is the same effect as if the function would finish without a return statement.

return results.push(played); returns the result of results.push(played);, which may not be undefined.

If you ignore the return value of your function recurse, there is no difference, which is the case in your function rockPaperScissors.

Upvotes: 1

Hunan Rostomyan
Hunan Rostomyan

Reputation: 2176

That's because recurse is only being used for its side-effects (namely, for what it does to results), not its value. The return is still necessary so that the recursion bottoms out, but other than that, there is no reason to return anything from recurse.

Upvotes: 1

Related Questions