While loop code

Using While loop in javascript?


'while' loop is used to execute a set of statements repeatedly until a condition works true. The difference between 'for' and 'while' loop is that 'while' does not take counter as an argument.
// set of statements that will be executed

As defined in the syntax, while loop has only one parameter, condition to be validated. The statements inside "while" will be executed until this condition becomes false.
For an example, we will consider a situation where we want to print first 5 number.


<script language="javascript">
var i=0;
document.write("The value of i is - "+i+" ");


The execution process is as,
a) The initialization of the variable "i" as 1 was done before starting the loop.
b) In while loop, the condition was checked,
the condition is satisfied (true) as i<5 and so the statements are executed.
c) In the last line of the statement we has increased or incremented the value of i by 1. So after the end of the loop the pointer goes back to the beginning of the loop and checks the condition.
d) Now "i" will be 1 and i is less than 5. The condition satisfies and the statements are executed. This continues till i is 5.
e) When i is five, the condition becomes false and the pointer comes out of the loop.
Note: The very important thing to note here is the i++ statement. If i++ has not been included 'i' will always be zero, so the condition will always be true and the loop becomes an infinite loop. This will cause memory issue or infinite loading of the page.

Ask Questions

Ask Question