By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

JavaScript while and For loops

Tutorial on how to work with JavaScript while and for loops.

Edited: 2012-12-30 08:15

JavaScript while and for loops are created using the while and for words, followed by curly brackets, while the code to be executed goes between the brackets.

Loops are used to repeat certain bits of code until a given condition is met. Sometimes you will also see loops, where the condition never will be met, making the loop run continuously, or until stopped by other means.

JavaScript while loop

For example, the while loop can repeat the code between the brackets, until a variable equals a given number, the number is incremented somewhere in the loop. A JavaScript while loop example is shown below:

var Counter = 0; // The loop counter

while(Counter <= 15){
	document.write("Count: " + Counter);
	document.write("<br>");
	Counter++; // Increments the Counter
}

In above example, the loop will run while the Counter is either less than or equal to 15 <=. You can also use different combinations of operators, leaving out the equals sign would simply make the loop stop at 14.

The Counter variable is incremented by using two plus + signs, these can either be placed at the beginning or the end. I.e. ++Counter or Counter++.

JavaScript for loop

The for loop is similar to the while loop, except that everything used to control the loop is moved the the loop statement. A JavaScript for loop example is shown below:

for(Counter = 0; Counter < 5; Counter++){
	document.write("Count: " + Counter);
	document.write("<br/>");
}

Above statement first sets the Counter variable to 0, and than it states that it should run while less than 5, the final argument simply increments the counter. You could also use minus signs, if you wanted the counter to count down instead. Also note that we didn't have to declare the variable, since its done in the loop statement it self.

See also

  1. How to use forEach