Writing A For Loop
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.