For Loops in JavaScript

A for loop is a type of loop that can repeat a block of code a set number of times. For example, you could use a for loop with a counter to repeat a set of instructions 10 times. However, for loops can be much more useful than that though. You could use a for loop to work through every character in a string or every element in an array to process each element (see the next tutorial).

A for loop has three parameters:

  • A counter variable (often called i which stands for index. It acts as a counter and tells the loop where to start counting from)
  • A condition (a condition that needs to evaluate to true for the loop to run its block of code)
  • An increment (the amount the counter variable will increase by each iteration of the loop eg. i++ would increment by 1, and i=i+3 would increment by 3

Every repetition of a loop is called an iteration. For example, if a for loop is set to repeat 10 times then that means the loop will have 10 iterations (it will iterate the code 10 times).

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

Take a look at the sample code below which shows how to create a for loop.

Here is the HTML code:

<html>
    <head>
        <title>For loops</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

Here is the JavaScript code:

// In this example, the counter called i starts at 0 and the loop starts when the counter is no longer lass than 10.
// The counter goes up by 1 for every iteration of the loop.

for(i=0; i < 10; i++){
    console.log(i);
}

console.log("Goodbye");

Next tutorial: Looping through arrays (and strings)