Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

JavaScript While Loop

Often in your code you will want to keep repeating a certain action. Maybe not forever, but until a certain condition is true. For this, we use the JavaScript while loop.

The while loop will continue executing until the condition within the parenthesis is true, with conditions similar to the if statement, like so:

var x = 10;
while (x != 15) {
x = x + 1;
document.write(x);
}

This example will output:

11
12
13
14
15

In JavaScript If, we saw how we could use if (variable) for a simple condition. Similarly, with while, you will often use while (variable) or while (!variable):

var x = 10;
while (x) {
x = x - 1;
}

This will bring x down to 0. The while loop will execute ten times, each time lowering the value of x by 1. This is because the condition only has to evaluate to true, it does not actually need to equal true. A value will evaluate to true if it is non-zero: usually a number greater than 0, any string (except an empty string). Therefore, the while loop will be executed as long as x is greater than 0.

Next, we'll learn JavaScript iteration with For.

« JavaScript If Statement JavaScript For Loop »

More JavaScript Tutorials:
» Secret Access
» Controlling Checkboxes with JavaScript
» Restoring Form Field Values
» Automatically Inserting the Current URL Into Forms
» Opening Popup Windows With No Extra Markup
» Sending Cookies By Email