Skip to content

What is a loop?

Photo by Steve Kirks

Learn to learn code faster, using techniques honed by years of study, neatly packaged into one book: How to Learn Code

When coding it is common to need to repeat lines of code. Loops help us do this in mass for all our coding needs. You can stuff anything into a block or section of code and make it repeat again and again.

This repetition is the center of all applications you use. This software I am using to type-it cycles on a while loop. I am using the Medium platform which likely uses Node on a loop. Your browser cycles with a while loop, your video games cycle one massive while loop. YouTube, Instagram, heck even ChatGPT cycles on a while loop. 

If you were to get on GitHub and look through most software-you are likely to find a main loop. A main loop controls a main thread from which all other code branches. 

Here is an example:

2012 Runescape Java Client

Notice the for loop here. That is the main loop for the entire Runescape client in 2012. All operations related to your Runescape game play spawn from that for loop. Game engines, graphics applications, rendering and anything with a UI does this.

The different kinds of loops

If you dedicate yourself to programming you will end up creating loops like these. When you do-different kinds of loops exist for specific use cases. You goal should be to learn which type of loop best fits your code logic. 

So lets start with three specific loops. They are the for, while and do while loops. These are the essential loops you will use in almost every application you write.

Basic For loop

The for loop uses the “for” keyword and creates 3 states which are pieced together. Take a look…

for (let i = 0; i < 5; i++)
console.log(i); // prints 0 1 2 3 4

Take a look at that code. It prints 0 1 2 3 4. Console.log is the print function which is repeated 5 times. It goes through 3 steps:

  1. Initialization: ‘let i = 0;’
  2. Condition: ‘i < 5;’
  3. Update: ‘i++’

We start ‘i’ off at zero. Then set a permanent condition to only continue looping if ‘i’ is less than 5. Lastly at the end of each loop block we add one to ‘i’.

With this we repeat the entire block under the loop 0 1 2 3 4 times. Which ends up being five times.

Lets see a bigger block used in a for loop:

for (let i = 0; i < 5; i++) {
console.log('This is iteration number:', i);
let square = i * i;
console.log('The square of', i, 'is', square);
console.log('Hello, World!');
console.log('Iteration completed.\n');
}

That entire block will be repeated 0 1 2 3 4 times which is five times…

Array for loop

We can select an element from an array like so….

const fruits = ['apple', 'banana', 'cherry'];

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

It’s the same thing as a basic for loop but instead of a plain number we use the length.

We can short hand this like so…

const fruits = ['apple', 'banana', 'cherry'];

for (const fruit of fruits) {
console.log(fruit);
}

These three versions of a for loop are used in all languages and everywhere out there in software. You cannot escape it. 

They do have different use cases. For some problems you need to know the current value of ‘i’. In others it is cleaner to just use the short hand. Others don’t even have an array. You learn when it is appropriate as you use them.

While loop

The particular use case of a while loop is their infinite cycling. You can run a while loop forever, unlike a for loop….

while(true)
console.log("hello");

As long as what is in parenthesis is true, the loop will run indefinitely. Even with big blocks and cycles.

while(true) {
console.log('This is iteration number:', i);
let square = i * i;
console.log('The square of', i, 'is', square);
console.log('Hello, World!');
console.log('Iteration completed.\n');
}

This will repeat all 5 lines of that code forever. Lets look at this…

let x = 0;
while(x != 5) {
x = x + 1;
console.log(x) // Prints 1 2 3 4 5
}

We run an infinite loop-a while loop. But we set an exit condition. So long as x is not 5 we can continue. So the code prints 1 2 3 4 5 then exits the loop.

Do-while loop

If we wanted to shift the values over. Or move the logic a little bit we can use a do while loop.

let i = 0;
do {
console.log(i); //prints 0 1 2 3 4
i++;
} while (i < 5);

The only difference between do while and a while loop is when the condition is checked. The condition is checked last and not first. This allows you to use a certain logic with it.

Do while loops are not a requirement for any project. All logic can be adjusted to use a regular while loop. In real programming do while loops are rare. 

How to continue

For all loops we can use two important keywords, break and continue. Lets see an example…

for (let i = 0; i < 5; i++) {
if (i == 3)
continue; // Skip 3
console.log(i); // prints 0 1 2 4
}

This is the same for loop as before but instead of printing 0 1 2 3 4 we want to print 0 1 2 4, skipping the 3. The same can be done for the while loop…

let x = 0;
while(x != 5) {
x = x + 1;
if(x == 3)
continue;
console.log(x) // Prints 1 2 4 5
}

How to break

Okay now lets use these two examples but with break.

for (let i = 0; i < 5; i++) {
if (i == 3)
break; // Exit at 3
console.log(i); // prints 0 1 2
}

We use the same for loop but instead of skipping at 3 we exit at 3. The same is true to while loops…

let x = 0;
while(x != 5) {
x = x + 1;
if(x == 3)
break; // Exit at 3
console.log(x) // Prints 1 2
}

At x == 3 we break and we print 1 and 2.

More loops

These loops are less commonly used but still useful. I have been coding for 7 years and know all 6 of these types of loops very well. These are great for when you are coding something that requires them. You won’t get confused if you can use them.

For each loop

For each loops are the most common here. They are applied to a stream of data where each element is acted upon. Almost all languages have these. JavaScript in particular uses for each quite a lot.

In languages like Python or Java you have to code these intentionally. You do not stumble on for each looping casually. There is usually a use case you are fulfilling.

But in JavaScript the language itself leads the programmer into using for each loops. Here is an example:

const fruits = ["Apple", "Banana", "Cherry"];

fruits.forEach((fruit) => {
console.log(fruit); // Prints "Apple Banana Cherry"
});

We take an array fruits and select each element to print out. From this forEach loop we create an instance of each element then do what we like.

Iterator-based loops

In languages like Python and Java, iterators and iterables are used to traverse through elements of a collection or sequence. These loops typically use methods like next() to iterate through the elements.

It looks something like this…

fruits = ["Apple", "Banana", "Cherry"]
iterator = iter(fruits)

while True:
try:
fruit = next(iterator) # Each element
print(fruit)
except StopIteration:
break

We separate the fruits array into individual memory then select one at a time. It is very similar to forEach. The use case for iterators is to break up some large data into smaller bits of memory. It uses way less memory this way. I hardly find myself using these but I could see them being used a lot when needed.

Recursive loops

Recursion is a function or method that calls itself. This process repeats until a final case is reached then exits. Take a look

function printArrayElement(arr, i = 0) {
if (i >= arr.length)
return;
console.log(arr[i]); // this is the action
printArrayElement(arr, i + 1);
}
const fruits = ["Apple", "Banana", "Cherry"];
printArrayElement(fruits);

We call the function within itself and perform some action. In this case we print the element of the array. We get “Apple Banana Cherry”. Once we reach the length of the array we exit the recursion.

Nesting loops

All of these loops can be nested within each other. Nesting loops is very common. Take a look at this 2D array…

const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

for (let i = 0; i < matrix.length; i++)
for (let j = 0; j < matrix[i].length; j++)
console.log(matrix[i][j]); // prints 1 2 3 4 5 6 7 8 9

Here we print out the entire matrix by going through each element and printing it out. The entire inner for loop completes before moving to the next element in the outer loop. You can nest any loop within any loop.

Learn to choose the right type of loop

Each type of loop fits a piece of logic differently. Reading & writing code, language models and trial & error teach us the use cases.

As an example-for loops are good for finite loops where you need it to end. These are great for when you cannot afford infinite looping. While loops are great for you need an infinite loop with a few exit conditions. Do while is great when you need infinite looping but you need to test the first loop.

In all my time coding I have only used recursive loops a 1 or 2 times in real coding. Everything possible in recursive loops is also possible in for or while loops.

However it is still good to know how to use them. For recursive loops LeetCode is good practice. For iterator based, you need to encounter a use case for them as you code.

I remember Unity and C# mods from video games used iterator looping. Outside that I never had to use them. One day in the future you may need them as part of a framework or SDK. When you do use them you will learn on the spot.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Search this blog

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Newsletter

Subscribe now to get my library of freebies + weekly emails with coding, tips for learning, and resource tips.

Learn to learn code faster, using techniques honed by years of study, neatly packaged into one book: How to Learn Code

Top content