I don't understand function return in javascript

前端 未结 3 1243
日久生厌
日久生厌 2021-01-15 08:20

Can anyone explain why javascript return statement is used in function? when and why we should use it?

Please help me.

3条回答
  •  我在风中等你
    2021-01-15 09:00

    You use a return statement for two reasons:

    1. To return a specific value from a function.

    2. To finish the execution of the function before the last line of code in the function.

    Without any return value; statement, the function does not return a specific value (technically the return value is undefined).

    Without a specific return statement somewhere in the function, the function runs until the last line of code in the function.

    Examples:

    function add(x, y) {
        // return a sum of the two arguments
        return x + y;
    }
    
    console.log(add(1, 3));    // 4
    
    
    function findParm(str, key) {
        if (!str || !key) {
             // invalid parameters, so return null
             return null;
        }
        var pieces = str.split("&");
        for (var i = 0; i < pieces.length; i++) {
            var loc = str.indexOf(pieces[i] + "=");
            if (loc >= 0) {
                // when we've found a match, return it and finish execution of the function
                return str.slice(loc + key.length + 1);
            }
        }
        // no match found, return null
        return null;
    }
    
    var str = "user=John&login=yes"
    findParam(str, "login");          // "yes"
    

提交回复
热议问题