The Factory Worker Analogy
Imagine you're a factory worker boxing products:
-
Without automation: You manually pack one box, seal it, label it. Then do the exact same thing for the next box. And the next. And the next. 1000 times.
-
With automation: You program a machine: "Repeat these steps until all products are boxed."
Loops are your automation.
Instead of writing the same code 100 times, you write it ONCE and tell the computer: "Keep doing this until I say stop."
Why Loops Matter
Without loops:
print("Hello Student 1")
print("Hello Student 2")
print("Hello Student 3")
... 997 more lines ...
print("Hello Student 1000")
That's 1000 lines of repetitive code!
With loops:
for each student from 1 to 1000:
print("Hello Student " + number)
Two lines. Same result. MUCH easier to maintain.
Loops power everything:
| Task | Loop Usage |
|---|---|
| Displaying a list of products | Loop through each product |
| Sending emails to subscribers | Loop through each subscriber |
| Calculating totals | Loop through each item, add to total |
| Searching | Loop until found or end reached |
| Animation frames | Loop and update position each frame |
The Two Main Types
1. FOR Loop: "Do This a Specific Number of Times"
Use when you know HOW MANY times to repeat.
FOR counter from 0 to 5:
do something
"Run 5 times, counting from 0 to 4"
Real-world examples:
- Print 10 receipts
- Show 20 products per page
- Retry an operation 3 times
2. WHILE Loop: "Keep Going Until a Condition Changes"
Use when you DON'T know how many times, but know WHEN to stop.
WHILE user hasn't typed "quit":
get input
process input
"Keep going until user says stop"
Real-world examples:
- Keep asking for password until correct
- Read file until end is reached
- Keep game running until player loses
How FOR Loops Work
A for loop has three parts:
for (START; CONDITION; UPDATE)
â â â
â â âââ "After each round, do this"
â âââ "Keep going while this is true"
âââ "Before starting, set this up"
Example (step-by-step):
for (let i = 0; i < 5; i++)
let i = 0 â Start at 0
i < 5 â Keep going while i is less than 5
i++ â After each round, add 1 to i
Rounds: 0, 1, 2, 3, 4 (5 total iterations)
Think of it like stairs:
Step 0: Do the task
Step 1: Do the task
Step 2: Do the task
Step 3: Do the task
Step 4: Do the task
Step 5: STOP (condition i < 5 is now false)
How WHILE Loops Work
A while loop checks the condition FIRST:
WHILE condition is true:
do something
(hopefully something changes the condition!)
Important: Make sure something inside the loop eventually makes the condition false, or it runs FOREVER!
attempts = 0
WHILE attempts < 3:
try to connect
if failed:
attempts = attempts + 1 â This changes the condition!
else:
break â Exit early if successful
For vs While: Quick Decision Guide
| Use FOR when... | Use WHILE when... |
|---|---|
| You know the count | Count is unknown |
| Looping through a list | Waiting for something |
| Fixed number of tries | User input validation |
| "Do this 10 times" | "Do this until done" |
Examples:
| Scenario | Common Choice |
|---|---|
| Print numbers 1-100 | FOR |
| Keep asking until valid password | WHILE |
| Process all 50 orders | FOR |
| Read file until end | WHILE |
Looping Through Collections
Most commonly, you loop through lists of things:
Loop through array with for...of:
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// "apple", "banana", "orange"
Loop through object keys with for...in:
const person = { name: "Alice", age: 30 };
for (const key in person) {
console.log(key + ": " + person[key]);
}
// "name: Alice", "age: 30"
Break and Continue: Loop Control
Break: "Stop the entire loop NOW"
Looking for Alice in a list of 1000 people...
Loop through each person:
If this is Alice:
BREAK! â Found her, no need to check remaining 999!
Continue: "Skip this one, move to next"
Processing orders, skip cancelled ones...
Loop through each order:
If order is cancelled:
CONTINUE â Skip this, check next order
Process the order
Common Mistakes
Mistake 1: Infinite Loops
The loop can run forever if the condition doesn't become false:
counter = 0
WHILE counter < 5:
print(counter)
// Forgot to increase counter!
// counter stays at 0 forever!
Fix: Make sure something changes the condition:
counter = 0
WHILE counter < 5:
print(counter)
counter = counter + 1 â Now it will eventually reach 5!
Mistake 2: Off-by-One Errors
The most common loop bug! You go one step too far or one step short.
Array has 5 items: [0, 1, 2, 3, 4]
Valid indices: 0, 1, 2, 3, 4
â for i from 0 to 5: â Index 5 doesn't exist!
â for i from 0 to 4: â Correct range
Mistake 3: Modifying While Looping
Don't change a list while you're looping through it:
â Loop through items:
If item is bad, remove it â Indices shift! You'll skip items!
â Create new list without bad items
FAQ
Q: Which loop is faster?
In modern code, the difference is negligible. Choose based on readability, not micro-optimizations.
Q: Can I nest loops?
Yes, but be careful! A loop inside a loop multiplies iterations:
- Outer loop: 100 times
- Inner loop: 100 times
- Total: 10,000 iterations!
Q: When should I use forEach vs for...of?
Use for...of when you need to break early or use async/await. Use forEach for simple iterations.
Q: How do I loop backwards?
Start at the end and decrease:
for i from length-1 down to 0:
print item[i]
Q: Should I use map/filter instead of loops?
For transforming data, yes! They're clearer for specific purposes:
map: Transform each itemfilter: Keep matching itemsreduce: Combine all items into one value
Q: What's an iterator?
An object that knows how to access items one at a time. for...of works with any iterator (arrays, strings, maps, etc).
Summary
Loops automate repetitive tasks. Instead of writing the same code 100 times, write it once and loop.
Key Takeaways:
- FOR: Use when you know how many times
- WHILE: Use when you know when to stop, but not how many times
- for...of: Loop through array values
- for...in: Loop through object keys
- break: Exit loop immediately
- continue: Skip to next iteration
- Watch for infinite loops (make sure something changes the condition!)
- Watch for off-by-one errors (check your boundaries)
Master loops and you can automate any repetitive task!
Leave a Comment
Comments (0)
Be the first to comment on this concept.
Comments are approved automatically.