iEntry 10th Anniversary CSS Snippets JavaScript Snippets

 
 





For, While, and Do While Loops

There are three different ways you can do loops in JavaScript. They all give you the same results, it is just a matter of personal preference, and performance, when choosing to use which one. In this tutorial we will take a closer look at each of the starting with the for loop.

The for loop can provide you with a cleaner looking code, but to people new to JavaScript it maybe a little confusing when first looking at or using a for loop. This is because you have to declare a variable, when to run the code, and how to increment the variable during each loop.

for (i = 0; i <= 10; i++){
	document.write (i + "
"); }

The while loop does the same thing except it is formated a little different. Instead of declaring the variable when you start the loop you have to declare the varible before the loop. Also, during the loop you will have to increment the variable, or else your code will enter a endless loop and will not stop looping.

var i = 0;
while (i <= 10){
	document.write (i + "
"); i++; }

The last loop you can use is the do while loop. This loop looks very similar to the while loop, but is formated a little different. Like the while loop, you have to declare the varible before the loop.

var i = 0;
do {
	document.write(i + "
"); i++; } while (i <= 10)