Loops: The `for` loop

The for loop is one of the most classic loops in programming.

Here’s the syntax.

We start by defining the 3 properties of the loop with semicolon, and then we add a block that’s executed for every iteration:

for (<initialization>; <condition>; <increment>) {

}

By <initialization> I mean we typically set up an index variable to 0, like let i = 0:

for (let i = 0; <condition>; <increment>) {

}

In the <condition> block we say how many times we want the loop to iterate, for example until i is less than the length of an array:

for (let i = 0; i < list.length; <increment>) {

}

Finally, in the third spot, we increment the index variable:

for (let i = 0; i < list.length; i++) {

}

Here’s a practical example, where we have a list array and we loop over it to print each value:

const list = ['a', 'b', 'c']

for (let i = 0; i < list.length; i++) {
  console.log(list[i])
}

This <initialization>; <condition>; <increment> setup is very powerful, because we can do things like looping in the opposite direction, or skip items, or only iterate a portion of an array, but it’s also quite tricky to learn at first.

Here’s a little demo that also shows how to work with the keywords break and continue to do some useful stuff:

Lessons in this unit:

0: Introduction
1: ▶︎ The `for` loop
2: The `do-while` loop
3: The `while` loop
4: The `for-of` loop
5: The `for-in` loop
6: Other kinds of loops
Want to learn more? Check out our courses