When to Use Each Loop Type
You'll learn how to pick the right loop for the job — for, for...of, or for...in — based on what you're working with.
The Right Tool for the Right Job
JavaScript gives you multiple loop types, but each has a sweet spot. Choosing wisely makes your code clearer and less error-prone.
Think of it like tools in a kitchen: you could cut bread with a steak knife, but a bread knife works better. Same with loops — match the loop to your data structure.
Decision Guide
Use for when:
- You need precise index control (counting backwards, skipping items, custom increments)
- You're working with numerical ranges or counters
- You need to modify the loop variable mid-loop
- Performance is critical in tight loops
Use for...of when:
- You're iterating over array values and don't need the index
- You're working with strings, Sets, Maps, or any iterable
- You want clean, readable code for simple iteration
- You care about the values, not their positions
Use for...in when:
- You're iterating over object property names (keys)
- You need to enumerate an object's own and inherited properties
- Avoid for arrays — it iterates keys as strings, not predictable order
Quick Reference
- Array values? →
for...of - Array indices matter? →
for(traditional) - Object keys? →
for...in(withhasOwnPropertycheck) - Sets/Maps? →
for...of - Complex counting? →
for
Key Takeaway: Use for...of for iterables when you want values, for...in for object keys, and traditional for when you need index control or performance tuning.