H I O X INDIA
Javascript Tutorial
 HOME  ||  Scripts  ||  Purchase  ||  Tutorials  ||  Images  ||  Tools  ||  Templates 
  :-)  Send Page   :-)   Feedback   :-)   Register   :-)   Links   :-)   Support   :-)
Español Français 中文 Deutsch Portuguese Japanese தமிழ்
 Forums   Hosting   Internet Stats   Easy Calculation   FUN Games 

Java-Script Tutorial
Introduction
Variables
Operators
Statements
Loops
Functions
Objects
Arrays
Browser Objects
Form DOM
Ask Your Doubts
More about Javascript
Feedback



while LOOP code & example


Topic

Using 'while' loop in javascript?



Explanation

while LOOP:
        '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.

Syntax:
while(condition)
{
     // 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.
Example Code:
<script language="javascript">
var i=0;
while(i<5)
{
document.write("The value of i is - "+i+" ");
i++;
}
</script>


Result:


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.





        Javascript (JS) is one of the most used languages in the world. Some times spelled as Java Script. Hope you enjoy this tutorial. Do send your feedback or suggestions on this javascript or java script tutorial. This is a copyright content.

privacy policy     license     sitemap
© 2004-2010 HIOX INDIA

Other Links