Loops: Repeating Without Copy-Paste
A loop runs the same code many times β often with a small change each pass. Loops are how you process every item in a list, retry a failed request, or animate a moving object.
From Bee: If your loop hangs the page, you have an infinite loop. The condition variable is not being updated. Stop the tab and check.
What Is a Loop?
A loop repeats a block of code. Two main shapes appear in every language:
- for β when you know how many times you want to repeat (e.g., "for each item in this list").
- while β when you stop on a condition (e.g., "until the user types quit").
For-of / For-in / Foreach
Modern languages provide cleaner ways to loop over collections without managing an index manually. Use them when you can β they're less error-prone than index-based loops.
Break and Continue
break exits the loop immediately. continue skips to the next iteration. Both are useful but overuse them and your loop becomes hard to follow.
Loop Visualizer
Pick a loop and step through it line by line. Watch i update and the console fill in.
Code Examples in Three Languages
// Classic for
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// for-of (cleaner)
const names = ["Aisha", "Ben", "Chen"];
for (const name of names) {
console.log(name);
}
// while
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
// break / continue
for (let i = 0; i < 10; i++) {
if (i === 5) break; // stop at 5
if (i % 2 === 0) continue; // skip evens
console.log(i); // 1, 3
}# for over a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# for over a list
names = ["Aisha", "Ben", "Chen"]
for name in names:
print(name)
# while
count = 0
while count < 3:
print(count)
count += 1
# break / continue
for i in range(10):
if i == 5:
break
if i % 2 == 0:
continue
print(i)// Classic for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Enhanced for (each)
String[] names = {"Aisha", "Ben", "Chen"};
for (String name : names) {
System.out.println(name);
}
// while
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}
// break / continue work the sameBest Practices
- Prefer
for-of/for-eachover manual index loops when you don't need the index. - Initialize loop variables right before the loop.
- Make sure your loop has a clear exit β infinite loops freeze programs.
- Avoid modifying a collection while looping over it.
Common Mistakes
- Off-by-one errors.
<vs<=determines whether the last item is included. - Infinite while loop. Forgetting to update the condition variable.
- Modifying the array while looping. Items get skipped or reprocessed.
- Reusing the same variable across nested loops.
ioutside,iinside β collision.
We have a dedicated Common Bugs with Loops page β five real broken snippets with the fix. Read it before you start writing.
How It Works Under the Hood
A for loop compiles into a sequence: initialize, test, execute body, update, jump back to test. The CPU does this in a tight cycle that's extremely fast β modern CPUs run billions of simple-loop iterations per second.
for-of and forEach add a layer of abstraction. They use the language's iterator protocol (Symbol.iterator in JS, __iter__ in Python). Iterators let you loop over things that aren't arrays β generators, streams, ranges, infinite sequences β using the same syntax.
This is why for (const line of fileStream) {} works in modern Node: the file stream implements the iterator protocol and yields one line at a time without ever loading the whole file.
From Beginner to Pro
The same concept gets deeper as you grow. Here's what mastery looks like at three levels:
You write for (let i = 0; i < n; i++) and access elements with arr[i].
You prefer for (const x of arr) when you don't need the index. You use break and continue deliberately.
You reach for map, filter, reduce when transforming data. You write generators for lazy iteration. You profile before optimizing β and know that JIT-compiled for loops are usually faster than chained array methods on hot paths.
Performance & Gotchas
- Off-by-one with
<vs<=. - Modifying the collection during iteration β splice removes shift indexes.
- Closure-in-loop with
var(legacy JS) β all callbacks see the final value. - Infinite while loops β usually a missing increment or a condition that never flips.
Authoritative references: MDN β for, Python β for, Oracle β Java for, Wikipedia β Iterator pattern.
Quick Quiz
Real-World Uses (Production Code, Today)
Rendering a feed
Twitter / X loops over your timeline array and renders one post per item. Without loops, every UI list would be impossible.
Retry policy
When an API call fails, code typically loops up to 3 times before giving up: for (let attempt = 0; attempt < 3; attempt++).
Game animation
Every game uses a "main loop" β 60 times per second, redraw the screen, check input, update positions. The whole game is one big while (running).
Frequently Asked Questions
When do I use for vs while?
for when you know the count or you're iterating a collection. while when you stop on a condition.
What's a do-while loop?
Like while, but the body runs at least once before the condition is checked. Less common in modern code.
How do I loop a fixed number of times in Python?
for i in range(n): β runs n times, with i taking values 0 through n-1.
What does break do?
Exits the innermost loop immediately.
What does continue do?
Skips the rest of the current iteration and moves to the next one.
Can I loop over a string?
Yes β strings are sequences of characters, so for-of / for-in works on them in all three languages.
What's an infinite loop?
A loop whose condition never becomes false. Sometimes intentional (servers, games); usually a bug.
Are loops slow?
Modern hardware runs millions of iterations per second. Don't worry about loop speed until profiling shows it matters.
Related Concepts
Data Types in Programming
Related concept.
Strings
Related concept.
Operators
Related concept.
- Loops: Repeating Without Copy-Paste is one of the 13 universal concepts of programming.
- The syntax differs across languages, but the underlying idea is the same.
- Practice in the playground to make it stick.