Bookmark and Share

JavaScript While Loop

The while loop is an advanced programming technique that allows you to do something over and over while a conditional statement is true. Although the general uses of the while loop are usually a bit complex, this lesson will teach you the basics of how to create a while loop in JavaScript.

Advertise on Tizag.com

JavaScript While Loop Explained

There are two key parts to a JavaScript while loop:

  1. The conditional statement which must be True for the while loop's code to be executed.
  2. The while loop's code that is contained in curly braces "{ and }" will be executed if the condition is True.

When a while loop begins, the JavaScript interpreter checks if the condition statement is true. If it is, the code between the curly braces is executed. At the end of the code segment "}", the while loop loops back to the condition statement and begins again.

If the condition statement is always True, then you will never exit the while loop, so be very careful when using while loops!

Creating a Simple While Loop

This example shows how to create a basic while loop that will execute a document.write 10 times and then exit the loop statement.

JavaScript Code:

<script type="text/javascript">
<!--
var myCounter = 0;
var linebreak = "<br />";
document.write("While loop is beginning");
document.write(linebreak);

while(myCounter < 10){
	document.write("myCounter = " + myCounter);
	document.write(linebreak);
	myCounter++;
}

document.write("While loop is finished!");
</script>

Display:

Our variable myCounter started off at 0, which is less than 10, so our while loop executed its code. The value 0 was printed to the browser and then myCounter was incremented by 1 and the while loop started over again.

1 was less than 10 so the while loop's code was executed... and the process repeats itself a few more times until...

myCounter was 10 which was not less than 10 so the while loop's code did not execute. You can see this in the Display: because the last value to be printed out was 9.

Note: Advanced programmers may recognize that a for loop would be a better solution for this example, but we hope you can ignore this for our needs to create an easy example!

Bookmark and Share




Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials