by Dinesh Thakur Category: JavaScript Tutorial

JavaScript While Loop just looks at a short comparison and repeats until the comparison is no longer true. To begin, take a look at the general syntax for Script the first line of a While Loop: 

while (count<11)

The While Loop does not create a variable the way a for loop can. When using a While Loop, you must remember to declare the variable you wish to use and assign it a value before you insert it. 

while ((count>4)&&(count<11))

This time, the loop runs only while the variable in script is greater than 4 and less than 11. For the While loop to run at all, the initial value of the variable would need to be within that range; otherwise, the While loop would be skipped entirely.

The following script shows the general structure of a full While Loop so that you can see how it looks:

var count=1;


while (count<6)
  {
    While Loop Code Here count++;
}

First, notice that the value of 1 is assigned to the variable count before the Java Script While loop begins. This is important to do so that the While loop in Java Script will run the way you expect it to run. This While loop is set up to repeat five times, given the initial value of the variable and the increase in the value of the variable by 1 each time through (count++).

In a While Loop, you must also remember to change the value of the variable you use so that you do not get stuck in a permanent while loop. If the previous sample While Loop had not included the count++ in script, the While Loop would have repeated indefinitely, and you do not want that to happen. So, the main things you must remember with a while loop are to give the variable an initial value before the loop and to adjust the value of the variable within the while loop itself.

For an example of the Java Script while loop in action, you can re script your sentence-repeat script to work with a while loop:

document.write("Java Script While Loop Example.<br />");

var count=1;
while (count<11) {
document.write(count+". I am part of a While loop!<br />");
count++;}
document.write("Now we are back to the plain text.");

In many cases, you can choose to use a for loop or a while loop based on personal preference, since they can perform many of the same tasks. As far as nesting with javascript while loop, it works the same as with the for loop. You can insert another javascript while loop, a for loop, or an if/else block within a JavaScript While Loop . You can also insert a JavaScript While Loop within the other statement blocks if you wish.



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.