Page 379 - Webapplication11_C11_Flipbook
P. 379
On running the above program, we get the following output:
Infinite Loop
An infinite loop is a piece of code that never ends because it never reaches the ending condition. An infinite loop might
cause your software or browser to fail and your machine to become unresponsive. In order to avoid such situations,
we must be aware of infinite loops and how to avoid them.
Let’s look at some examples of how infinite loops can occur. When the while statement’s condition is set to true, one
of the most typical infinite loops occurs as shown:
var i=5;
while (true) {
document.write(i); // execute code forever
}
By omitting all parts of the head of a for() block, you can easily wind up in an infinite loop :
for ( ; ;) {
//statements are will execute forever
}
How do you avoid becoming stuck in an infinite loop?
Ð ÐWithin the for() loop: Ensure that the statements in the for() block never affect the value of the loop counter
variable to avoid ending up in an infinite loop. If they do, your loop can terminate prematurely or loop indefinitely.
Ð ÐLoops in while and do-while: Ensure that the loop has at least one statement that changes the value of the
comparison variable. (That is, the variable used in the comparison statement of the loop.) Otherwise, the condition
may always return true, resulting in an endless cycle.
Ð ÐNever leave the terminating condition to the user’s discretion: The user may thoughtlessly cancel the prompt box
etc. which may prevent the loop from terminating.
Lab Assignment ‘n Activity #Experiential Learning
1. Predict the output of the following code:
<html>
<body text="green">
<h2>Using do...while loop in JavaScript</h2>
<script>
/* to find the sum of positive numbers entered by user. The loop terminates
when the user enters a negative number,and that negative number is not
added to the sum */
JavaScript Part 1 377

