A count-controlled loop that runs for a certain number of iterations.

There is probably a programming language out there that does not have some sort of implementation of the for loop, but they are few and far between. It is almost a requirement in order to have the computer do code repeatedly a certain number of times.

The loop contains a counter or index that the programmer defines. The code will run and loop back to the top as long as the "continue condition" is true. Each loop iteration needs to modify the index somehow or else you have an infinite loop. Typically you increase the index by 1 but you can do any sort of mathematical operation on the index.


The syntax is fairly simple:

for (index start value; continue condition; index modifier) {
    // code

Example 1 - Hello World

// The following prints "Hello World!" 5 times, showing the line number
// Start at 1, end before 6 (so, 5), increase by 1 every interation
for ( let index = 1; index < 6; index++ ) {

    console.log(`${index}: Hello world!`);


Example 2 - Animation

Here is an animation of a for loop in action. The code prints the powers of 2 from a power of zero to ten (inclusive). It also keeps track of a running total and prints that at the end.

For a faster animation, click here (and for a really fast one, click here).

Example 3 - Decrement

While most examples and definitions show i++ to increment the index, it does not need to be counting up. You can decrement (subtract one), add 2, multiply by a value... it all depends on the needs of the programmer. Here is an example of a for loop that counts down by 1:

// Print from 20 (inclusive) to -10 (exclusive)
// Start at 20, loop if greater than -10 (so stop after -9), decrease by 1 each loop
for (let i = 20; i > -10; i--) {

Example 4 - Nested Loops

Because a for loop can contain any amount of code (scope block { }), you can write another for loop inside (and another inside that, etc). This is called nested looping. An example would be printing a multiplication table or other 2-dimensional work:

// Print the multiplication table from 1 to 10 (inclusive)
let output;

// Rows (1 top, 10 bottom)
for (let y = 1; y <= 10; y++) {
    output = ''; // Make sure it is a string
    // Columns (1 left, 10 right)
    for (let x = 1; x <= 10; x++) {
        // Build the output row
        output += x*y + "\t";
    // Print the current row

More Information

If you need more information, here are some other sources:

Last updated