it is happening due to the scope of variable w . in this case it is declared with var keyword , that makes it having global scope and it is accessible outside of for loop. at some point w equals 2 and w++ happends, for loop body is not executed, but the value of w is set to 3 anyway and it is accessible in that function with name printNamm .