I don't understand why a function will run the remaining code after a return is called
function func(i) {
while (i >= 0) {
if (i < 0) {
return;
}
document.write("inside loop, i is " + i);
document.write("</br>");
i--;
} //end of while
document.write("end of function, i is " + i);
document.write("</br>");
}
func(2);
Output:
inside loop, i is 2;
inside loop, i is 1;
inside loop, i is 0;
end of function, i is -1;
I was expecting:
inside loop, i is 2;
inside loop, i is 1;
inside loop, i is 0;
-
I don't understand why it executes "end of function, i is -1" if a return is called?
-
If I replace while(i >= 0) with while(true) the function gives the expected output (without the last document.write). Why is that?
-
If after the while loop I replace the code with:
return document.write("end of function, i is " + i); document.write("end 2 of function, i is " + i);
the last code line (end 2 of function, i is ) is not executed. Why the code keeps executing after the first return and not after the second?
-
If I take the return out of the if statement the function stops when return is called:
while (i >= 0) { document.write("inside loop, i is " + i); document.write("</br>"); i--; return; }
output is:
inside loop, i is 2
Why the last document.write ("end of function, i is " ) doesn't execute in this case ?
Aucun commentaire:
Enregistrer un commentaire