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