mercredi 24 juillet 2019

Why a function executes remaining code even if it encounters a return (return inside if inside a loop inside function)

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; 

  1. I don't understand why it executes "end of function, i is -1" if a return is called?

  2. If I replace while(i >= 0) with while(true) the function gives the expected output (without the last document.write). Why is that?

  3. 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?

  1. 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