Let’s Review For Loops in JavaScript

Can you imagine if loops did not exist in programming? All the extra lines of code we would have to write, talk about carpel tunnel! Now, when I first started learning JavaScript, I had a difficult time understanding the function of loops and how to apply them, especially a for loop. Turns out, once I understood how they work and I applied them to my code, they were actually fun to use. In this article, I will cover the basics of for loops in JavaScript, including how to write them and some common use cases. Let's jump to it!

Writing A For Loop

For loops can be used to iterate over a set of data or perform a specific action a certain number of times. The loop consists of three parts: the initialization, the condition and the increment. The following is the basic syntax for a for loop in JavaScript:

In this example, the loop will run 10 times. The initialization sets the starting value of the loop variable 'i ' to 0. The condition specifies that the loop should continue as long as 'i ' is less than 10. So, the increment increases the value of 'i ' every time the loop runs (at the end of each iteration).

Let's break the loop down a little more. The initialization runs just once, to set up the loop variable. Every time the loop runs, the condition statement is evaluated. If you don't set a condition, your for loop will run infinitely. The final expression, which is your increment, is evaluated at the end of each loop iteration. You can increment or decrement your loops with this expression.

Common Use Cases

A common use case for a loop is to iterate over an array. You can have a loop iterate over an array and log each element to the console like this:

Which will give you the following results in the console:

Having a loop perform a specific number of times is my favorite. In the following example, the loop will run 5 times and log ‘Hello’ to the console each time.

How does this for loop work? Let's take a closer look.

I set my counter at 0 (i = 0), so the first time the loop runs it will console log 'Hello' then increase i by one, making i = 1. The loop will continue to iterate, increasing the value of i, and console logging 'Hello' until the condition i < 5 is met. Want to take it a step further and print 'Hello' to the DOM? Let's do it!

For this, I created a function with a loop that prints 'Hello' 5 times to the DOM. My function has a for loop, but this time I use .innerText to print to the DOM. I make sure to append 'Hello' by adding +=, otherwise it will be printed so fast, it will seem like 'Hello' was only printed once. Here is what it looks like:

....and my results (in hot pink, because why not!) in the DOM:

That's all for now, amigos! Hope you're enjoying my content.