var printNumTwo;
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
I understand that there is only one i in this snippet, and it is a global one.
But why does it return 3?
I thought the loop stopped at 2?
If the loop stopped at 2 why the global i is three?
The for loop runs before the console.log(printNumTwo()) line, so after the for loop is finish i = 3, so when you execute the function printNumTwo, it returns the value of global value of i.
Why would it stop at 2? You have nothing in your code which would stop the loop.
i guess because the return is inside the anonymous function it wont break out from the for loop. but if their is a return statement in the if statement too , i++ will not happen one more time
so in the above example, the function will get executed when i === 2 but it will only break out of the function right and continue along… however if we add a break statement in the if statement after the function passes, then it breaks out of the for loop as well. Can we somehow make it break out of the for loop my defining a break or return inside the function ? i think thats what im confused about
No, the function will not get executed until the for loop finishes. When i ===2, the function definition for printNumTwo is created. If you add a break statement on the line after the function definition, then yes it will stop the loop after i ===2 and the value 2 will be returned by the function.
Putting a break inside the printNumTwo function definition will not affect the outer for loop.
I don’t understand the meaning of this line of code " printNumTwo = function(); "
Sir i don’t understand the behaviors of loop.
Please comment on my understanding of for loop whether i understood correct or not.
for(var i = 0 ; i < 3 ; i++)
List item
First " i" initialize to 0;
After than i checked with 3 whether less then or not if condition is true then it start executing code of inside the FOR loop.
After the completion on code inside the for loop.The value of " i " variable is incremented by " i++ ".