For and Nested Loops
Learn about for loops and nested loops.
We'll cover the following...
For loops
For loops are one of the most common types of loops and can be found in most programming languages. They take the following form:
for (initialization ; condition ; update) {
// do something
}
Three things get set inside the parentheses:
- The initialization code is run before the loop starts and is usually employed to initialize any variables that are used in the loop.
- The condition has to be satisfied for the loop to continue.
- The update code is what to do after each iteration of the loop, and it is typically used to update any values.
This process is illustrated in the following diagram.
For the Ten Green Bottles song, we would have to initialize the number of bottles to . The condition would be that this number has to be more than zero and the update code would be to reduce the number of bottles by . This is shown in the diagram above.
Let’s try running the following code:
for (let bottles = 10; bottles > 0; bottles--) {console.log(`There were ${bottles} green bottles, hanging on a wall. And if one green bottle should accidentally fall, there'd be ${bottles - 1} green bottles hanging on the wall`);}
This initializes the variable bottles
to , then sets the condition to be bottles > 0
, and uses the decrement operator bottles--
to reduce the
value of the bottles
variable by one after every loop.
The results should be exactly the same as before. In fact, you may have noticed that it’s possible to use a while loop, a do–while loop, or a for loop to achieve exactly the same results.
A for loop is generally considered clearer (and is definitely more popular looking at code examples around the Web), probably because all the details of the loop (the initialization, condition, and update code) are all in one place and kept out of the actual code block.
Nested loops
We can place a loop inside another loop to create a nested loop. These have an inner loop that runs all the way through before the next step of the outer loop occurs. This can be seen visually in the diagram below.
As we can see, the inner loop runs all the way through for every step of the outer loop. ...