Learning JavaScript: for Loops

Mike McMillan
Level Up Coding
Published in
5 min readAug 18, 2020

--

Photo by Priscilla Du Preez on Unsplash

In this article I’m going to cover the different forms of the for loop that are available in JavaScript. There is the general for loop, the for..in loop, and the for..of loop. I will describe how each loop works and when is the right time to use each loop type.

I am leaving out the Array.forEach loop as it is specialized for arrays and requires some knowledge of functions I haven’t covered yet.

The General for Loop

The first form of for loop I want to discuss is the general for loop that is standard in most programming languages. This loop is used in situations where you know in advance how many times you want the loop to iterate, as opposed to while loops, which should be used primarily when the number of iterations is unknown when the program is written, such as when you’re processing an unknown quantity of data or records in a file.

The syntax template for the general for loop is:

for (loop-variable-init; condition; loop-variable-modification) {
statement(s);
}

The loop variable is a variable that is initialized, tested, and then modified until it causes the condition to become false. Here is a simple example of a for loop that prints the numbers 1 through 10:

for (let i = 1; i <= 10; i++) {
putstr(i + " ");
}

The output from this program is:

1 2 3 4 5 6 7 8 9 10

Let’s see how this loop works with an array:

let names = ["Terri", "Meredith", "Allison", "Mason"];
for (let i = 0; i < names.length; i++) {
putstr(names[i] + " ");
}

This program outputs:

Terri Meredith Allison Mason

You can have more than one statement in the loop body. The following program accepts input from the user and displays the sum of the 5 numbers entered:

let total = 0;
let number = 0;
const numEntries = 5;
for (let i = 1; i <= numEntries; i++) {
putstr("Enter a number: ");
number = parseInt(readline());
total += number;
}
print("The total is: " + total);

Here is the output from one run of this program:

--

--

Mike McMillan writes about computer programming and running. See more of his writing and courses at https://mmcmillan.gumroad.com.