In the year and a half I took computer science courses in college, looping was my Achilles heel. There seemed to be so many different little parts and I struggled to understand how they all worked together. As I restarted my journey to become a software engineer, just the thought of looping filled me with dread. With this blog post, I am going to conquer my fear, further my understanding, and hopefully yours too!
The for loop has 4 different statements. Its basic structure looks like this:
Initialization: This is what is executed first. It can start loop counters and more complex expressions, but often it is used to declare a counter variable. Basically, it tells the loop what it needs to know or do to start.
Condition: This is what tells the loop to continue! As long as this condition is true, the loop continues to loop some more. Once this condition is false, the loop comes to a complete stop.
Iteration: This is what is executed at the end of each loop iteration. Often it involves incrementing or decrementing the counter variable you set in the initialization part of the for loop.
The three above statements are all separated by a semicolon.
Loop Body: This is the code that runs each time you go around the loop.
Let's look at a simple example:
For this example, the initialization is setting the variable of lives equal to 5. I imagine this to be how many lives you might start with while playing a video game.
The condition in this example states as long as lives is greater than zero continue to run. That means if lives is one or more the loop will loop again. Once lives reaches zero, the loop will stop.
The iteration states that after every loop happens, decrement lives by one. So once a loop occurs, there will be one less life.
In this loop body, we are just console logging a string that lets the user know how many lives they have remaining.
The result of this for loop in the console would be:
As you can see, the first console log shows the initialization of lives at 5. The last console log shows lives at 1 which means our loop did not run when lives reached 0, which is exactly what we wanted.
The while loop is similar to the for loop but it only has two statements. Its basic structure looks like this:
Condition: This is exactly like the condition in our for loop. If this condition is true, the loop will continue. If this condition is false, the loop stops.
Loop Body: Just like in our for loop, this is the code that will run every time your loop loops!
Let's use our lives example from before but this time we will use a while loop:
Our while loop looks similar to our for loop but there are some definite differences:
1.) Our variable initialization (let lives = 5) is done outside of our loop.
2.) Our iteration (lives--) is set inside of the loop body.
Even with these differences, our results are the same: