For Loops

A for loop is a loop that can run a set number of times. For example, you could use a for loop with a counter to repeat a set of instructions 10 times. Or you could use a for loop to cycle through every letter in a string or every element in an array (see the next tutorial). Every repetition of the loop is called an iteration.

Watch the video below and then scroll down to view the code.

Take a look at the sample code below which shows how to use a counter in a for loop.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // A FOR loop has three parameters separated by a semi-colon
 // The first parameter tells JavaScript where to start counting (eg. 0)
 // The second parameter is when to end the loop (eg. when the counter is no longer less than 10)
 // The last parameter is how much to increment the counter by (eg. i++ would increment by 1 and i=i+3 would increment by 3)
 
 for(i=0;i<10;i++){
 // in this example, the counter i starts at 0 and finishes at 10
 // the counter goes up by 1 for every iteration of the loop
 // While the counter is less than 10, the following line of code inside the loop will run:
 document.write("This is line "+i+"<br/>"); 
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Looping through arrays (and strings)