for loop will print out,
0 1 2 3 4 as expected, since those are the values of
i in the loop. In general programming terms this is known as a range. The parameters of a for statement describe a range. Think of it as an ordered list of values to iterate over.
Let's examine what happens to
i after the for loop. When
var is used in a
for statement it goes to the top of the scope the for statement is in. (Scope is just another word for environment, or memory block accessible by a function.) So it is still accessible after the loop. This is known as leakage. The new ES6 keyword,
LET elliminates that leakage, but that is for another discusssion. The point is that
i has a value after the loop,
The scariest part is the fact that
i does not change value inside the
do..while loop. That should be an infinite loop and crash your browser window. Lesson here: Never leave a control variable unchanged in a while loop (do while is a while loop.)
The neat thing about JS is that we change a value inside a statement.
It will print
i and increment it in one stroke. Search `JS prefix and postfix addition and subtraction' for more detail on this. This is an efficient way to deal with the problem of change.