For loops are very useful for iterating over sequences of elements.
To understand the value of for loops, let's take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.
Example: Greeting our friends
Imagine this: We have an array of friends and we want to greet each of them using a message template.
If we only use print(), our program might look like this:
let friends = ["Andy", "Mircea", "David", "Mary"]
print("Hey, " + friends[0])
print("Hey, " + friends[1])
print("Hey, " + friends[2])
print("Hey, " + friends[3])
That's ugly, but still manageable. After all, we're writing only 4 lines of code and most probably copying and pasting a few times.
Now imagine if we had 10, 100 friends? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.
We'll learn how for loops come to our rescue in the next lesson. But for now, let's gain an appreciation for them.
Assignment
Follow the Coding Tutorial to see how frustrating our life is without for loops.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.