Loops: Don't Repeat Yourself
Make the computer do the hard work while you relax.
Computers never get tired. They don't complain about doing the same thing a million times. We use Loops to give a command once and tell the computer how many times to repeat it.
- What a "Loop" is and why it saves time.
- How to write a
forloop. - How to use a counter to keep track of repeats.
This is for the "Smart-Lazy" student. If you have a list of 500 students and you need to send them all the same email, you don't want to click "Send" 500 times. You want a loop!
Think about a Race Track:
- Start: You begin at Lap 1.
- Action: You run around the track.
- Check: Have you finished 10 laps?
- Repeat: If NO, run again. If YES, stop!
A loop is just the computer running laps around your code.
The for loop has three parts inside its parentheses ():
- Start: Where do we begin? (Usually at 0).
- Condition: When do we stop? (e.g., as long as we are under 5).
- Step: How do we count? (Add 1 every time).
We use i++ as a shortcut for "Add 1 to the count".
➜
COUNT +1
YES? Go again! 🔄
NO? Exit! 🚪
Let's make the computer count from 1 to 5. We use let i = 1 to create a counter that can change.
// Start at 1; Stop at 5; Add 1 each time
for (let i = 1; i <= 5; i++) {
// This happens 5 times!
Logger.log("Current Number: " + i);
}
}
Copy this and change the 5 to 10 or 20!
Your log will show the message repeated perfectly with the updated number each time:
Running lap number: 1
Running lap number: 2
Running lap number: 3
Running lap number: 4
Running lap number: 5
Race Finished! 🎉
Click to avoid breaking your browser!
1. The Infinite Loop: If you forget to add i++, the count stays at 1 forever. The computer will keep running the loop until it crashes! 😱
2. Semicolons: Inside the for(), you MUST use semicolons ; to separate the three parts. If you use commas, it will fail.
3. Wrong Direction: If you start at 10 and say i++ (add 1) while trying to reach 1, the condition will never be met. Be careful with your math!
Write a script that logs the sentence: "I will always use Google Apps Script" exactly 10 times. Can you make it show the number (1 to 10) next to the sentence?
Instagram uses loops to show you posts. It says: "For every post in my database that my user likes, show it on their screen." Without loops, your feed would only have one picture!
You’ve unlocked the power of automation! Loops allow you to repeat complex tasks instantly. Instead of writing 100 lines of code, you can now write 3 lines and let the computer do the rest.
Status: Efficiency Expert 🔄 | Level: Automation Pilot ✈️