A deeper look into for() loops
While going through this weeks lessons at GA’s WDI program I noticed that quite a few people were having trouble understanding exactly what the for() loop was doing. That lead me to do some deeper research into the details about scope and usages for the for() loops.
First I found it best to break the loop down into its components. First you declare it is a for loop with the keyword “for”. In the parenthesis are three optional(shortcut) areas to pass information to the for loop. Last is the code block to be run.
The first optional data area is a location that will allow you to declare any variables. This is often used to keep an index counter to iterate through an array but allows any values to be declared. This data is actually in the same scope the for() loop is in but the data is also discarded after the loop is finished.
The second optional data area is a conditional statement that will be checked after your code block has already run. If it is true, the block will be run again. A for loop does not require a conditional statement. If left out, you will need to add a break command to escape the loop or the loop will run until your page breaks.
The last optional data area is a group of code to run after the block of code has been run but before the conditional statement is checked. This will often be i++ or using the += or -= to set an increment to make your counter jump. This gives you a way to change a value that your conditional statement will check. If you leave that out it can be much easier to create a never ending loop. You do not need it in the for statement if you are changing the value somewhere in the block of code to be run.
Hopefully by understanding the parts of the loop a greater understanding of in what situations you can use and in what situations it is not appropriate to use the for() loop. It might help others to remember that the inner parts of the for() loop are there for your convince and there are other ways to create the same commands in different locations. The loop is most often used when you are needing to iterate through an array through a set interval but it is still important to understand and consider the function of the loop.