Skip to main content

🔁 Loops

A repeating alarm clock

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:

TaskLoop Usage
Displaying a list of productsLoop through each product
Sending emails to subscribersLoop through each subscriber
Calculating totalsLoop through each item, add to total
SearchingLoop until found or end reached
Animation framesLoop 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 countCount is unknown
Looping through a listWaiting for something
Fixed number of triesUser input validation
"Do this 10 times""Do this until done"

Examples:

ScenarioCommon Choice
Print numbers 1-100FOR
Keep asking until valid passwordWHILE
Process all 50 ordersFOR
Read file until endWHILE

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 item
  • filter: Keep matching items
  • reduce: 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.