简体   繁体   中英

Console.log and function return (Javascript)

Apologies if this has been asked before, I am a relative newcomer to coding and not so sure about the keywords to search for.

This function assigns some random values for later timeout:

function getDelays(tonesTotal){
    var return_array = new Array();
    for (var i = 0; i < tonesTotal; i++)
    {
        var r = getRandInt(0, 600);    
        var delay = r * 1000;
        return_array.push(delay);  
    }
    console.log(return_array);
    return return_array; 
}

In this manner, the console properly logs return_array ... but flip the order:

    return return_array; 
    console.log(return_array);

... and the console is silent. Why?

The return statement exits the current function.

No further code will run.

The return statement ends function execution and specifies a value to be returned to the function caller.

Which in effect means, anything after the return statement will not be reached, and thus not executed. There are IDE editors that will warn you about this problem.

The return statement exits the function and the next code statements are not run. If you use a linter tool like ESLint, JSLint they will show a warning that unreachable code is detected .

The return statement ends function execution and specifies a value to be returned to the function caller. If you don't specify a value in the return statement and use it like return the function returns undefined .

The return statement exits program execution out of a function and back to where the function was called. The reason why console.log() is not called is because if the return statement executes, all code underneath that function is never reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM