Loops
for, while & Iteration
Loops let you repeat code multiple times without writing it over and over. JavaScript has several loop types - each optimized for different situations.
A loop is like a Ferris wheel - it goes round and round, each rotation doing the same thing but with different passengers (values). It stops when you decide (condition becomes false or break is called).
🔑 Key Concepts
Best when you know exactly how many iterations you need. Compact init + condition + increment.
while checks condition before each run. do-while always runs at least once then checks.
Modern, clean iteration over arrays & iterables. forEach gives index too.
💻 Code Examples
⚠️ Common Mistakes
Forgetting to increment - infinite loop crash!
Always ensure the loop condition eventually becomes false. i++ is your friend.
i <= array.length (off-by-one error)
Arrays are 0-indexed, so the last index is length-1. Use i < array.length.
Using for...in on arrays
for...in is for OBJECTS (iterates keys as strings). Use for...of or forEach for arrays.
📋 Quick Reference
Live Code Playground
Edit the code and press ▶ Run to see output instantly.