What I fail to understand is, even if the console is a closure of setTimeout, how does the value of j become 4 if the condition we set in the for loop is that j <=3?
It will run three times and will only stop the 4th time when the condition of execution of 3 times ( j<= 3 ) is met. That value was 4. It will remember the value of j from the last iteration of the loop and show 4.
The main function is only executed thrice and we get the answer accordingly. What is happening is that since it's a closure, it will store the value after j<= 3, which is 4, when it is stopping. Hence, that value will be stored in j and only that will be accessible, that's why we see 4. In order to avoid this case, where we only get the value of the end, we use the solutions mentioned! Nirmal Shah