| You are here: | About>Computing & Technology>JavaScript> Javascript Tutorials> Learn Javascript> The WHILE Loop |
![]() | JavaScript |
Learn JavascriptThe WHILE LoopJoin the DiscussionMore of this TutorialRelated TermsIntroductionEven easier to use than the for loop is the while loop. A while loop doesn't initialize or increment any fields automatically as part of the command, it just tests a condition and executes the loop for as long as the condition remains true.
Looping with WhileLet's begin by looking at a simple while statement:
var x = 0;
while (x<10) { document.write(x); x++; } The above example produces the numbers from 0 through 9 just as in the example in the last tutorial. The difference is that this time we need to initialize the variable before the start of the loop and increment the variable before the end of the loop. A common error when using the while loop is to forget to do anything that might change the value being tested on while statement from within the loop. If the variable being tested is not changed within the loop then the condition will either never be true and the loop will therefore never get executed or it will always be true and will execute forever. One trick some programmers use if the looping conditions are extremely complicated is to set the loop up so that it will loop forever and then code a number of if statements within the loop to test for when to terminate the loop. Here is the same while loop recoded to work that way (of course with such a simple condition to test we wouldn't bother to do it in this instance).
var i=0;
while (true) { if (i >= 10) break; document.write(i); i++; } Do WhileThe while loop discussed above tests the condition before running the code within the loop each time. If the condition is not met the first time it is tested then the content of the loop never gets run. Sometimes we want the loop to run at least one regardless. We can achieve this by shifting the test to the end of the loop like this:
var x = 12;
do { document.write(x); x++; } while (x<10) In this example the loop will execute once even though the original value of x is greater than that tested for in the while condition. Using What You KnowA while loop can easily be substituted whereever you have a for loop by moving the initialization statement in front of the loop and the increment statement to just inside the end of the loop. You may find that doing this makes the loop easier to read. Past Lessons |
|
All Topics | Email Article | | | ![]() |
| Advertising Info | News & Events | Work at About | SiteMap | Reprints | Help | Our Story | Be a Guide |
| User Agreement | Ethics Policy | Patent Info. | Privacy Policy | ©2008 About, Inc., A part of The New York Times Company. All rights reserved. |


