Infinite loops

When you initially work with loops, you may create infinite loops. An infinite loop executes indefinitely. An infinite loop does not stop executing because the stopping condition is never reached. An infinite loop can freeze your computer, making your computer unresponsive to your commands. To avoid such problems, make sure to properly initialize the counter, make sure the terminating condition is eventually met with the proper updates to the counter variable. As an example, consider the following infinite for loop:

for (j = 100; j >= 5; j++)

Do you know why is this an infinite for loop? Note j is initialized to 100 and each time the loop is executed, we add 1. Thus each time the for loop will execute the value of j will go up by 1, it will never reach 5, our stopping condition.

As you may guess, you could also create an infinite while loop. The following shows how:

<script language="javascript">
var i = 2;
while (i <= 10) {
document.write (i + "<br>");
i -= 2;
}
</script>

In the above while loop, i will always remain less than 10 because each time the loop will be executed, i will be decremented by 2.