For loops

Coding with JavaScript

🕑 This lesson will take about 10 minutes

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 lesson).

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.

Sample HTML and JavaScript code