As kids, we planted a windbreak on our farm. We also planted a line of trees that needed watering a few times a week. We turned on the hose, watered the first tree, and counted to ten. Then, we moved to the second tree and repeated the process.
Similar to life our computer programs must repeat things. That’s where loops come in handy. For loops are quite common so let’s start there.
for
If we have an array of books and we would like to print them out. We could use the following loop.
for (let i = 0; i < books.length; i++) {
text += books[i] + "<br>";
}
The for loop has three basic parts. Start, Condition, and Step.
start
This is the part where we set up the loop variable. In our example that is i. Usually, we initialize to zero. Although, you can set it to say 10 and then count down too.
condition
Next is the condition where check to see if we need to run this loop again. Our example checks if we still have more books to loop through. If we are done we stop.
step
The last part is the step. This tells us what happens after each iteration. Our example uses the increment operator(++). This is the normal step but we can do other things for special cases.
while
If my dog Baxter wants to eat I want to create a loop that feeds him while he is hungry. The while loop can do this. Here is an example.
let baxterHungry = true;
while (baxterHungry) {
console.log(feedBaxter);
checKBaxter();
}
We set the variable to true. Then we feed the dog until it becomes false. The while loop evaluates the condition we give it. It needs to resolve to be true or false.
If it is true the code inside the loop executes. We evaluate the condition again. Once the condition becomes false the loop stops.
do-while
The for and while loops check the condition then run the code statements. The do-while is different in that it runs the code and then checks your condition. It is less common but useful in special situations.
let donutsEaten = 0;
do {
console.log("Donuts eaten " + donutsEaten);
donutsEaten++;
} while (donutsEaten < 5)
console.log("I'm full of Donuts!");
The do while runs until the condition is false—Opposite of the two other types of loops we have discussed. The output would look like this.
Donuts eaten 0
Donuts eaten 1
Donuts eaten 2
Donuts eaten 3
Donuts eaten 4
I'm full of Donuts!
When you need to loop through code JavaScript has a few options for you. Like other programming languages, it has the for, while, and do-while loops. Just make sure it fits your needs.