When to use return, and what happens to returned data?

后端 未结 5 2044
野趣味
野趣味 2021-02-01 07:50

What is the difference between:

function bla1(x){console.log(x)}

and

function bla(x){return console.log(x)}

I

5条回答
  •  天涯浪人
    2021-02-01 08:31

    With return you specify what the value of a function is. You can use this value to do further operations or to store it into a variable and so on.

    Since console.log returns undefined, the examples in your question are equivalent, as a function not reaching a return statement will return undefined as well. But let me give you an example:

    function sum(arr) {
        var s = 0;
        for (var index in arr) {
            s += arr[index];
        }
        return s;
    }
    
    function prodsum(arr, scalar) {
        return scalar * sum(arr);
    }
    
    console.log(prodsum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
    

    The result will be 165. If we remove the returns, then both functions will return undefined:

    function sum(arr) {
        var s = 0;
        for (var index in arr) {
            s += arr[index];
        }
        s;
    }
    
    function prodsum(arr, scalar) {
        scalar * sum(arr);
    }
    
    console.log(prodsum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
    

    and the result will be undefined as well. Basically, if you want the function to have a conclusion or final value, then you have a return in it.

提交回复
热议问题