JavaScript Iteration & Flow Control
Beyond basic loops, JavaScript offers specialized iteration methods and flow control statements.
for...of — Arrays & Iterables
The simplest way to iterate over arrays:
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: apple, banana, orange
Works on arrays, strings, Maps, Sets, and any iterable object.
for...in — Object Keys
Used specifically for iterating over object properties:
let person = { name: "John", age: 25, city: "NYC" };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: John, age: 25, city: NYC
Remember: Use hasOwnProperty to avoid inherited prototype properties.
break — Exit Early
let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
if (num === 3) {
console.log("Found 3!");
break;
}
}
// Output: 1, 2, Found 3!
continue — Skip Iteration
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) continue;
console.log(i); // 0, 2, 4, 6, 8
}
Labels — Break Nested Loops
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
console.log(`${i}, ${j}`);
}
}
// Output: 0,0 0,1 0,2 1,0
Without labels, break only exits the innermost loop.
Complete Example: Count Vowels
let text = "Hello World";
let vowels = "aeiouAEIOU";
let count = 0;
for (let char of text) {
if (vowels.includes(char)) {
count++;
}
}
console.log(`Vowels: ${count}`); // 3
Complete Example: Find First Match
let numbers = [1, 3, 5, 8, 9, 10];
let firstEven = null;
for (let num of numbers) {
if (num % 2 === 0) {
firstEven = num;
break;
}
}
console.log(firstEven); // 8
Best Practices
- Use
for...offor arrays — Cleaner syntax - Use
for...infor objects — Iterate over keys - Use
breakfor early exit — Don’t iterate unnecessarily - Use
continueto skip — Avoid nested if/else - Use labels sparingly — Can be confusing
Common Mistakes
- Using
for...inon arrays — Usefor...ofinstead - Forgetting
hasOwnProperty— Gets prototype properties - Breaking wrong loop — Use labels for nested
- Overusing
continue— Can make code hard to read - Not checking empty arrays — Always check length first