Loops
EasyLoops repeat code until a condition is met. JavaScript has for, while, do-while, for...of (arrays), and for...in (objects). Choose the right loop for your use case!
Interactive Visualization
Code
1const fruits = ['apple', 'banana', 'cherry']23for (let i = 0; i < fruits.length; i++) {4 console.log(fruits[i])5}
Loop State
Iteration:0
i:-
i < 3 = false
Console Output
No output yet
Step 1/13We create an array with 3 fruits. This is the data we want to loop through.
Key Insight:The for loop has 3 parts: initialization (let i = 0), condition (i < length), and update (i++). The condition is checked BEFORE each iteration.
Key Points
- for: when you know how many iterations
- while: when you don't know how many iterations
- for...of: iterate over array VALUES
- for...in: iterate over object KEYS
- break: exit loop early, continue: skip to next iteration
Code Examples
for Loop
// Classic for loop for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4 } // Looping through array const fruits = ["apple", "banana", "cherry"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
for(init; condition; increment) - most versatile loop
while Loop
// while: check condition first let count = 0; while (count < 3) { console.log(count); count++; } // 0, 1, 2 // do-while: runs at least once let x = 10; do { console.log(x); // runs once even though x >= 3 } while (x < 3);
while checks before running, do-while runs then checks
for...of (Arrays)
const colors = ["red", "green", "blue"]; // Iterate over VALUES for (const color of colors) { console.log(color); } // "red", "green", "blue" // Works with strings too! for (const char of "Hello") { console.log(char); // "H", "e", "l", "l", "o" }
for...of gives you values directly (best for arrays)
for...in (Objects)
const person = { name: "Alice", age: 25 }; // Iterate over KEYS for (const key in person) { console.log(key, person[key]); } // "name" "Alice" // "age" 25 // Warning: for...in on arrays gives indices as strings! const arr = ["a", "b"]; for (const i in arr) { console.log(typeof i); // "string" not "number"! }
for...in iterates over keys (use for objects, not arrays)
break and continue
// break: exit loop completely for (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i); } // 0, 1, 2, 3, 4 (stops at 5) // continue: skip to next iteration for (let i = 0; i < 5; i++) { if (i === 2) continue; console.log(i); } // 0, 1, 3, 4 (skips 2)
break exits the loop, continue skips current iteration
Common Mistakes
- Using for...in on arrays (use for...of instead)
- Infinite loops: forgetting to update the counter
- Off-by-one errors: < vs <= in conditions
Interview Tips
- Know when to use for...of vs for...in
- Explain why for...in gives string indices
- Show how to exit a loop early with break