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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!