Reputation: 1333
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?
Upvotes: 1
Views: 5132
Reputation: 6141
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.
Upvotes: 2
Reputation: 577
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.
Upvotes: 0
Reputation: 9908
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
.
Upvotes: 0
Reputation: 887887
The return
statement exits the current function.
No further code will run.
Upvotes: 2