Home 14: For loops
Content
Cancel

14: For loops

Next we have a look at for-loops. They work similar to a while loop, but the variable to count the iterations is already included. Like the while-loop, the for-loop also needs a condition to define how often a specific action-block should be repeated.

Here you can see the same example before, but with a for-loop instead:

1
2
3
for (let i = 0; i < 5; i++) {
  console.log(i);
}

On first sight it looks more compact and shorter. The reason for that is that we are doing three things in the first line. First, we define the counter-variable, in this case i, next we define the condition: i < 5, and last we define what should happen after every iteration. In this case it is i++, and this is a common shorthand syntax for i = i + 1 in JavaScript. So we increase i by 1 everytime after we have exectured the action-block. All statements in this line are separated by a semicolon ;.

Usually, we try to avoid naming our variables with single letters, but in this case it is common practice to call this counter-variables just i. If you like, you can give it a different name, for example count, iteration, …

Sometimes there are specific reasons to use a for-loop or a while-loop, but most of the times it is your decision what works best for you. If you want to count through things or loop over a list, a for-loop is the preferred choice. If you are working with random numbers for example and you don’t know how often your loop should be executed, a while-loop is the preferred choice.

This post is licensed under CC BY 4.0 by the author.